java常规编程:如何从“get”方法返回两种类型的原语('int和'string')?
正在尝试使用“get”方法打印对象的age
和name
。但是,我的get方法return
类型是string:
public String displayProfile() {
System.out.print(getName() + getAge());
因此出现了错误:
This method must return a result of type String
这里是我的主要方法:如果用户从“菜单”输入'2',其中(2==profile)程序应该显示用户的name
和age
旁注:要从菜单中选择“朋友”,用户将输入“3”(3=朋友)
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());
}
}
}
作为编程新手,我想培养良好的编程实践,因此要牢记这一点;你会如何从一个方法中显示不同类型的age
和name
[int=age和string=name],比如public String displayProfile()
或者这是完全错误的吗?那么还有什么选择呢强>
另外:
我的getName()
方法:
// GET NAME
public String getName() {
return this.name;
}
我的setName()
方法:
// SET NAME
public void setName(String name) {
this.name = name;
}
我的getAge()
方法:
// GET AGE
public int getAge() {
return this.age;
}
我的setAge()
方法:
// SET AGE
public void setAge(int age) {
age = this.age;
}
# 1 楼答案
可以将
String.format()
与格式说明符(%s, %d, %f...
)一起使用注意
return
语句。它与System.out.print(...)
完全不同另外,
setAge()
方法的主体应该如下所示:因为您想将作为参数传递的
age
分配给成员this.age