[英]Conventional Programming: How do you return two Types of primitive ('int and 'string') from “get” method?
Trying to print out age
and name
of an Object using "get" method. 尝试使用“get”方法打印出对象的
age
和name
。 However, my get method return
type is string: 但是,我的get方法
return
类型是字符串:
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
. 这是我的主要方法:如果用户从“菜单”输入“2”, 其中(2 == profile)程序应显示用户的
name
和age
。
Side note: To select "friends" from menu, user will enter '3' (3 = friends). 附注:要从菜单中选择“朋友”,用户将输入“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());
}
}
}
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 ie public String displayProfile()
OR is this completely wrong? 你将如何显示
age
和name
从像即一个方法不同类型[INT =年龄和string =名称] public String displayProfile()
或这是完全错误的? Then what are the alternatives? 那有什么选择呢?
Additionally : 另外 :
My getName()
method: 我的
getName()
方法:
// GET NAME
public String getName() {
return this.name;
}
My setName()
method: 我的
setName()
方法:
// SET NAME
public void setName(String name) {
this.name = name;
}
My getAge()
method: 我的
getAge()
方法:
// GET AGE
public int getAge() {
return this.age;
}
My setAge()
method: 我的
setAge()
方法:
// SET AGE
public void setAge(int age) {
age = this.age;
}
You can use String.format()
with format specifiers ( %s, %d, %f...
) 您可以使用带有格式说明符的
String.format()
( %s, %d, %f...
)
public static String displayProfile()
{
return String.format("%s %d", "StackOverflow", 6);
}
Note the return
statement. 请注意
return
语句。 It's totally different than System.out.print(...)
它与
System.out.print(...)
完全不同
Also, the body of setAge()
method, should look like: 另外,
setAge()
方法的主体应该如下所示:
this.age = age;
since you want to assign the age
passed as parameter to the member this.age
因为您要将作为参数传递的
age
分配给成员this.age
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.