有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java常规编程:如何从“get”方法返回两种类型的原语('int和'string')?

正在尝试使用“get”方法打印对象的agename。但是,我的get方法return类型是string:

public String displayProfile() {
    System.out.print(getName() + getAge());

因此出现了错误:

This method must return a result of type String

这里是我的主要方法:如果用户从“菜单”输入'2',其中(2==profile)程序应该显示用户的nameage

旁注:要从菜单中选择“朋友”,用户将输入“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());
        }
     }
       }

作为编程新手,我想培养良好的编程实践,因此要牢记这一点;你会如何从一个方法中显示不同类型的agename[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) 个答案

  1. # 1 楼答案

    可以将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