问题
Trying to print out age
and name
of an Object using "get" method. However, my get method return
type is string:
public String displayProfile() {
System.out.print(getName() + getAge());
Hence the error:
This method must return a result of type String
Here is my main method: if user enters '2' from the "menu" where (2 == profile) the program should display user's name
and age
.
Side note: To select "friends" from menu, user will enter '3' (3 = friends).
public static void main(String[] args) {
// Initializing Objects
People zac = new People();
zac.setName("zac");
zac.setAge(18);
People lisa = new People();
lisa.setName("lisa");
lisa.setAge(19);
// Zac be-friend LISA
zac.addFriend("lisa");
openApp();
if(optionSelected == 3)
{
System.out.println(zac.getFriend());
else if (optionSelected == 2) {
System.out.println(zac.displayProfile());
}
}
}
Being new to programming, I want to develop good programming practices, hence with this in mind; how would you display age
and name
of different type [int = age and string = name] from one method like i.e. public String displayProfile()
OR is this completely wrong? Then what are the alternatives?
Additionally:
My getName()
method:
// GET NAME
public String getName() {
return this.name;
}
My setName()
method:
// SET NAME
public void setName(String name) {
this.name = name;
}
My getAge()
method:
// GET AGE
public int getAge() {
return this.age;
}
My setAge()
method:
// SET AGE
public void setAge(int age) {
age = this.age;
}
回答1:
You can use String.format()
with format specifiers (%s, %d, %f...
)
public static String displayProfile()
{
return String.format("%s %d", "StackOverflow", 6);
}
Note the return
statement. It's totally different than System.out.print(...)
Also, the body of setAge()
method, should look like:
this.age = age;
since you want to assign the age
passed as parameter to the member this.age
来源:https://stackoverflow.com/questions/21794804/conventional-programming-how-do-you-return-two-types-of-primitive-int-and-st