gpt4 book ai didi

java - 常规编程: How do you return two Types of primitive ('int and ' string') from "get" method?

转载 作者:行者123 更新时间:2023-12-02 06:12:06 32 4
gpt4 key购买 nike

尝试使用“get”方法打印对象的agename。但是,我的 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] 的 agename或者这是完全错误的吗?那么还有什么替代方案呢?

另外:

我的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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com