EDIT: Thanks for all the answers! I didn't know that the object p
in List.java is different from the p
in Main.java. I passed it as a parameter and it works fine now. Thank you!
In Main.java:
System.out.println("Enter your name:");
String name = scan.next();
name+=scan.nextLine();
String words[]=name.split("\\s");
String capitalizeWord="";
for(String w:words){
String first=w.substring(0,1);
String afterfirst=w.substring(1);
capitalizeWord+=first.toUpperCase()+afterfirst+" ";
}
Person p = new Person(capitalizeWord);
In Person.java
private String name;
private int age;
Person(String newName){
name=newName;
}
Person(int newAge){
age=newAge;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
In List.java:
public void printInvoice(){
System.out.println("Enter your age:");
int age = scan.nextInt();
Person p = new Person(age);
System.out.println("Thank you for shopping with us, "+p.getName());
}
The last output is
Thank you for shopping with us, null
I don't know why this is happening. Did I do something wrong? I think the code is correct?
Each time you call a constructor you get a distinct instance of the object. The object created in Main.java
with a name is stored in a local variable p
that is only existing in the scope of Main.java
. In List.java
you create a second object with an age, but no name. It's also stored in a variable called p
but that one is in the scope of List.java
only and has nothing to do with the earlier created object.
It sounds like you want to add the name to the earlier object and not create a new one. For that you should pass the first object as a parameter to the code that adds the age, perhaps like this:
public void addAge(Person p) {
System.out.println("Enter your age:");
int age = scan.nextInt();
p.setAge(age); // will have to make this method in the Person class
System.out.println("Thank you for shopping with us, "+p.getName());
}
Calling Person p = new Person(age);
gives a brand new Person object that has no name yet.