作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
尝试使用“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 ==个人资料)程序应显示用户的姓名
和年龄
。
旁注:要从菜单中选择“ friend ”,用户将输入“3”(3 = friend )。
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());
}
}
}
作为编程新手,我想开发良好的编程实践,因此考虑到这一点;如何通过一种方法(例如 public String displayProfile()
)显示不同类型 [int = Age and string = name] 的 age
和 name
或者这是完全错误的吗?那么还有什么替代方案呢?
另外:
我的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;
}
最佳答案
您可以将String.format()
与格式说明符(%s、%d、%f...
)一起使用
public static String displayProfile()
{
return String.format("%s %d", "StackOverflow", 6);
}
注意return
语句。它与 System.out.print(...)
此外,setAge()
方法的主体应如下所示:
this.age = age;
因为您想要将作为参数传递的age
分配给成员this.age
关于java - 常规编程: How do you return two Types of primitive ('int and ' string') from "get" method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21794804/
我是一名优秀的程序员,十分优秀!