I am trying to print the individual objects in the players class(performance, injured and name) and on the main class I am trying to print the entire player object however when I try executing the toString(); method on both classes, I just receive player#2eb3998c or Main#37e6e526. Where am I going wrong?
Thanks for any help.
Player class:
package com.laurens;
/**
* Created by laurensvanoorschot on 20-01-16.
*/
public class player {
private String name;
private int performance;
private boolean injured;
public player(int performance, boolean injured, String name) {
this.injured = injured;
this.name = name;
this.performance = performance;
}
public boolean isInjured() {
return injured;
}
public void setInjured(boolean injured) {
this.injured = injured;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPerformance() {
return performance;
}
public void setPerformance(int performance) {
this.performance = performance;
}
#Override
public String toString() {
return "com.laurens.player{" +
"injured=" + injured +
", name='" + name + '\'' +
", performance=" + performance +
'}';
}
}
main Class:
package com.laurens;
public class Main {
private player player;
public static void main(String[] args) {
player player = new player (4, true, "laurens");
player.toString();
}
public com.laurens.player getPlayer() {
return player;
}
#Override
public String toString() {
return super.toString();
}
public void setPlayer (int performance, String name) {
if (performance < 4) {
boolean injured = true;
}
}
}
Most likely, you simply forgot to recompile your classes; your Player code is fine (and you have errors in your Main class that you aren't aware of, which suggests no recompile). That said, there's nothing in your posted code that actually prints anything. System.out.println (actually, any PrintWriter print methods) will automatically call toString() on an object, so there's no need to do that yourself, just
System.out.println(player);
Use
System.out.println(player.toString());
toString() returns a string/textual representation of the object. How to use the toString method in Java?
Explicitly calling print, displays your properties fine:
System.out.println(player.toString());
as well as:
System.out.println(player);
Related
I'm new in Java :] and I have a little problem with my app:
Why when I run it, it keeps saying me "null" even when person.setname("John")
I tried to fix it but without good result, what is wrong here and why?
I tried to debug it - same result - setName set name to John but anyway it keeps printing "null"
Really strange for new user like me.
If someone can help, or even try to say me what's wrong i'd be glad, thanks.
class App {
public static void main(String[] args) throws InterruptedException {
List<String> blacklist = Arrays.asList("Bill, Adam, Jessie");
;
Person person = new PersonWithBlacklistedCheck(
new PersonWithNullCheck(new Person()),
blacklist);
person.setName("John");
System.out.println("Person: " + person);
}
}
class PersonWithBlacklistedCheck extends Person {
private final List<String> blacklist;
private final Person target;
PersonWithBlacklistedCheck(Person target, List<String> blacklist) {
this.target = target;
this.blacklist = blacklist;
}
#Override
public String getName() {
return target.getName();
}
#Override
public void setName(String name) {
if (this.blacklist.contains(name)) {
throw new RuntimeException("[" + name + "] cannot be used as a name! it is blacklisted");
}
target.setName(name);
}
}
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class PersonWithNullCheck extends Person {
private final Person target;
PersonWithNullCheck(Person target) {
this.target = target;
}
#Override
public String getName() {
return target.getName();
}
#Override
public void setName(String name) {
if (name == null) {
throw new RuntimeException("[name] must not be null!!");
}
target.setName(name);
}
}
You have person object containing another person called "target" and another one "target" :
Blacklist should look like this:
List<String> blacklist = Arrays.asList("Bill", "Adam", "Jessie");
You were creating one entry: "Bill, Adam, Jessie".
You were doing some unnecessary metods override, adding unnecessary objects - when you extend class you have that object "person" already there, you don't need to put it as another object "target". If you want to have both null check and blacklist check executed before setting name you can extend classes in hierarchy: Person -> PersonWithNullCheck -> PersonWithBlacklistedCheck. Now setName() method will be executed in each of classes as ordered. Here's a fixed solution:
public class Test {
public static void main(String[] args) {
List<String> blacklist = Arrays.asList("Bill", "Adam", "Jessie");
Person person = new PersonWithBlacklistedCheck(blacklist);
person.setName("John");
System.out.println("Person: " + person);
}
}
class PersonWithBlacklistedCheck extends PersonWithNullCheck {
private final List<String> blacklist;
PersonWithBlacklistedCheck(List<String> blacklist) {
this.blacklist = blacklist;
}
#Override
public void setName(String name) {
if (this.blacklist.contains(name)) {
throw new RuntimeException("[" + name + "] cannot be used as a name! it is blacklisted");
}
super.setName(name);
}
}
class PersonWithNullCheck extends Person {
#Override
public void setName(String name) {
if (name == null) {
throw new RuntimeException("[name] must not be null!!");
}
super.setName(name);
}
}
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
This question was asked in my recent coding round. Its kind of tricky as we cannot modify getClass() and getClass().getName()
along with main method, Given are Food and FoodFactory class templates.
I had to print the following lines:
My name is Fastfood.
My name is Fruits.
Our superclass is Food
I'm serving Fastfood
I'm serving Fruit
Code:
/* Name of the class has to be "Main" only if the class is public. */
class FoodFactory{
public Food getFood(String string) {
// TODO Auto-generated method stub
return new Food(string);
}
public String toString(){
return "Food";
}
public static String getName(){
return "Food";
}
}
class Food{
String name;
public Food(String string) {
this.name = string;
}
public void servesFood() {
System.out.println("I'm serving "+name);
}
public String getName(){
return name;
}
}
class Solution
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
foodFactory myFoods = new foodFactory();
Food food1 = myFoods.getFood("Fastfood");
Food food2 = myFoods.getFood("Fruits");
System.out.println("My name is: " + food1.getClass().getName());
System.out.println("My name is: " + food2.getClass().getName());
System.out.println("Our superclass is: " + food1.getClass().getSuperclass().getName());
food1.servesFood();
food2.servesFood();
}
}
The key thing for this exercise is revealed by one word in your example output: superclass.
You want that getClass().getName() gives you different output. In order to get there, surprise: the objects you call getClass().getName() on ... need to have different classes!
Something like
class Food {
public void servesFood(){
System.out.println("I'm serving Food");
}
}
class FastFood extends Food {
#Override
public void servesFood(){
System.out.println("I'm serving Fastfood");
}
... similar for Fruit
If you now create instances of those two objects, they will give you the expected output. Now the question is: how are instances created?!
That is where your factory comes in:
class FoodFactory {
public Food getFood(String name) {
switch(name) {
case "FastFood" : return new Fastfood();
case "Fruit" : return new Fruit();
default: return new Food();
}
}
Please note: the above implementation assumes that any food that is not "Fastfood" or "Fruit"... is real "Food". And of course: you might expect that the actual "name" of the fruit ends up as some field within your Food class, but such refinements/extensions are left as exercise to the reader.
Here are the implementations of the two classes.
class FoodFactory{
private String name;
public Food getFood(String name){
this.name = name;
Food food = new Food(name);
return food;
}
public String getName{
return name;
}
}
class Food extends FoodFactory{
private String name;
public Food(String name){
this.name = name;
}
public void servesFood(){
System.out.println("I'm serving "+ name);
}
public String getName(){
return name;
}
}
This should work.
This one will work.
class FoodFactory extends Food {
public Food getFood(String string) {
if (string.equals("Fruit")) {
return new Fruit("Fruit");
} else {
return new FastFood("FastFood");
}
}
}
class Fruit extends Food {
public Fruit(String name1) {
super.name = name1;
}
}
class FastFood extends Food {
public FastFood(String name1) {
super.name = name1;
}
}
class Food {
public String name = null;
public Food() {
}
public Food(String string) {
this.name = string;
}
public void servesFood() {
System.out.println("I'm serving " + this.name);
}
}
class Solution1 {
public static void main(String[] args) throws java.lang.Exception {
FoodFactory myFoods = new FoodFactory();
Food food1 = myFoods.getFood("FastFood");
Food food2 = myFoods.getFood("Fruit");
System.out.println("My name is: " + food1.getClass().getName());
System.out.println("My name is: " + food2.getClass().getName());
System.out.println("Our superclass is: "
+ food1.getClass().getSuperclass().getName());// modification
food1.servesFood();
food2.servesFood();
}
}
I'm new to Java and i've been bashing my head over the wall to solve this problem. Anyway below is a class that creates a Person and below that, is a class that creates a Phonebook using an ArrayList of type Person. I want to write the remove function (in order to remove a Person from the list) but my problem is that since i only get the name of the person i can't use the Indexof function (cause it requires object) to get at what position lies the name.
This is my first time using an ArrayList to store an Object so i'm not even sure
how my results would appear. I'm guessing that if the position of the name (in my list) is 10 then 11 would be the phone and 12 would be the address. Am i correct?
public class Person
{
private String name;
private String phone;
private String address;
public Person (String n, String p, String a)
{
this.name = n;
this.phone = p;
this.address = a;
}
public void setPhone(String newPhone)
{
this.phone = newPhone;
}
public String getName()
{
return this.name;
}
public String getPhone()
{
return this.phone;
}
public String getAddress()
{
return this.address;
}
public String print()
{
return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}
}
import java.util.*;
public class phoneBook
{
Scanner in = new Scanner ( System.in );
private ArrayList <Person> persons = new ArrayList <Person>();
private int i;
private boolean flag;
public void addPerson(Person p)
{
persons.add(p);
}
public void listPersons ()
{
System.out.println(persons);
}
public void lookUp (String theName)
{
flag = persons.contains(theName);
if ( flag == true )
{
System.out.println("That name exists!");
}
else
{
System.out.println("That name does not exist!");
}
}
public void remove (String theName)
{
}
Edit: I'm planning to use the Scanner in another function. Don't worry about it.
I'm not sure of if do you want to get the object of that array, but each object is indexed to that array (with full attributes), now you can remove it by using the following code,
public String removePerson(ArrayList<Person> arrayList,String name)
{
for(Person currentPerson:arrayList)
{
if(currentPerson.getName().equals(name))
{
arrayList.remove(currentPerson);
return "Removed successfully"
}
}
return "No record found for that person";
}
just pass the arrayList and the name of that person to this method
You should override the equals() and hashCode() methods in the Person class. This way you will define when two objects of this type will be considered equal. Then you can use list.contains(yourObject) to determine if that object is equal to any object in your list, this based on your equals() implementation.
Does this help you?
public void remove (String theName,ArrayList<Person> persons) {
for (int i = 0; i < persons.size();++i) {
if(persons[i].getName().equals(theName)) {
persons.remove(i);
}
}
}
Best regards, Nazar
I am getting a Exception in Thread main
java.lang.NoSuchMethodException: com.laurens.Main.main([Ljava.lang.String;)
at java.lang.Class.getMethod(Class.java:1786)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:125)
Can someone explain where I am going wrong here?
Main
package com.laurens;
public class Main {
private player player;
public Main(com.laurens.player player) {
this.player = player;
}
public com.laurens.player getPlayer() {
return player;
}
public void setPlayer (int performance, String name) {
if (performance < 4) {
boolean injured = true;
}
}
#Override
public String toString() {
return "com.laurens.Main{" +
"player=" + player +
'}';
}
}
player
package com.laurens;
/**
* Created by laurensvanoorschot on 20-01-16.
*/
public class player {
private String name;
private int performance;
private boolean injured;
public player(int performance, boolean injured, String name) {
this.injured = injured;
this.name = name;
this.performance = performance;
}
public boolean isInjured() {
return injured;
}
public void setInjured(boolean injured) {
this.injured = injured;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPerformance() {
return performance;
}
public void setPerformance(int performance) {
this.performance = performance;
}
}
You don't have a method called main, which is what it is looking for to run your program. Notice that when you create a template application for a java console application in intelliJ it has a method:
public static void main(string[] args) {
}
That needs to be there for your program to run.
I have a couple to class in which I'm getting and setting a few things and then finally calling it in my main method. But when I call my class in the main method it just gives me the object instead of name,address and age. I know this structure is very complicated but I want to keep this structure because later on I will be adding a lot of things to this. It would be AMAZING if someone could tell me how to do this. I would really appreciate this. Below is my code for all my classes
This is my first class
public class methodOne
{
public String getName()
{
String name = "UserOne";
return name;
}
public int getAge()
{
int age = 17;
return age;
}
public String getAddress()
{
String address = "United States";
return address;
}
}
This is my second class
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is my third class
public class methodThree {
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
public methodThree()
{
this.methodOneInMethodThree = new methodOne();
this.methodTwoInMethodThree = new methodTwo(methodOneInMethodThree);
}
public methodTwo getMethodTwoInMethodThree() {
return methodTwoInMethodThree;
}
public void setMethodTwoInMethodThree(methodTwo methodTwoInMethodThree) {
this.methodTwoInMethodThree = methodTwoInMethodThree;
}
}
This is my fourth class which is the method maker
public class methodMaker {
public methodThree brandNewFunction(methodTwo object)
{
methodThree thirdMethod = new methodThree();
thirdMethod.setMethodTwoInMethodThree(object);
return thirdMethod;
}
}
This is my main class which calls methodMaker. What I want to achieve is that when I print the value it should print the name,address and age but instead it just prints trial.methodThree#4de5ed7b
public class mainClass {
public static void main(String args[])
{
methodMaker makerOfMethods = new methodMaker();
methodOne one = new methodOne();
methodTwo object = new methodTwo(one);
System.out.println(makerOfMethods.brandNewFunction(object).toString());
}
}
What you need to do is to override the default implementation of the .toString() method in the objects you want to print out:
#Override
public String toString()
{
return "Name: " + this.name;
}
EDIT:
I do not know exactly where you are printing, and you naming convention doesn't really help out, but from what I am understanding, you would need to implement it in all of you classes since they all seem to be related to each other.
So, in your methodOne class (can also be applied to methodTwo):
#Override
public String toString()
{
return "Name: " + this.name + " Age: " + this.age + " Address: + " this.address;
}
In your methodThree class:
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
#Override
public String toString()
{
StringBulder sb = new StringBuilder();
if(this.methodTwoInMethodThree != null)
{
sb.append("Method 2:").append(methodTwoInMethodThree.toString());
}
if(methodOneInMethodThree != null)
{
sb.append("Method 1:").append(methodOneInMethodThree.toString());
}
return sb.toString();
}
When you call
MyClass myObject = new MyClass();
System.out.println(myObject);
Implicitly , java calls instead
System.out.println(myObject.toString());
So, if in MyClass, you override toString(), then whatever your toString method returns is what's gonna be printed.
Side note: are you confusing classes and methods? Methods are functions in your classes, classes are wrappers around a bunch of attributes and methods. Your naming is confusing.
try this code:
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return name+" "+address+" "+age;
}
}
Are you printing the object using println()?
From the docs, println():
calls at first String.valueOf(x) to get the printed object's string value
This string value is obtained from the object's toString() method, which:
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object
So if you want to print anything other than this you have to override the toString() method in your object and return a string containing whatever you want.
Just google "override tostring java" and you will see a ton of examples.