【问题标题】:Return type required/ Cannot return a value from a method with a void result type需要返回类型/无法从具有 void 结果类型的方法返回值
【发布时间】:2017-03-29 17:20:18
【问题描述】:

我是初学者,你能告诉我我做错了什么吗?为什么我不能正确使用这些方法?

IDE 显示:需要返回类型/无法从具有 void 结果类型的方法返回值

`公共类人类

{
    public int Age = 0;
    public int Weight = 0;
    public int Height = 0;
    private String name = "";
    boolean isMale;
}

public getAge()
{
    return Age;
}
public getWeight()
{
    return Weight;
}
public getHeight()
{
    return Height;
}
public Human(int Age, int Weight, int Height, String name, boolean 
isMale)
{

}      `

【问题讨论】:

  • public int getAge(), public int getWeight() 等等... 另外,在驼峰式中以大写字母开头调用变量是一种不好的做法,这种风格主要用于类。
  • 我现在感觉很弱智:D 谢谢

标签: java


【解决方案1】:

到目前为止做得很好,您只是缺少方法的返回类型语句。你的方法应该写成如下:

class Human {
    private int Age = 0;
    private int Weight = 0;
    private int Height = 0;
    private String name = "";
    private boolean isMale;

    public int getAge() {
        return Age;
    }

    public int getWeight() {
        return Weight;
    }

    public int getHeight() {
        return Height;
    }

    public Human(int Age, int Weight, int Height, String name, boolean isMale) {
        this.Age = Age;
        this.Weight = Weight;
        this.Height = Height;
        this.name = name;
        this.isMale = isMale;

        //returns nothing
    }
}

请注意,每个方法都有某种返回类型。由于 getAge() 返回 Age(您在上面已将其指定为 int 类型),因此您需要在方法声明语句中显式放入您要返回一个 int 的语句。如果您要返回字符串或布尔值等,同样适用。

然而,最后一个方法(Human())是一个构造函数,当你实例化一个新的 Human 对象时会调用它:

Human myHuman = new Human(31, 155, 68, "Bob", true);

请注意,在上面的代码块中,我按照构造函数中的顺序传递值,并且构造函数根据传递的内容设置对象的属性。根据您的问题,这里最大的收获是它不返回任何内容(新对象除外......再次讨论)。

一般来说,如果您不返回任何内容,请将 void 放在返回类型中。就像您在 Main 函数中所做的那样。

我想指出的最后一件事是,在属性和方法中使用公共与私有。一般来说,您会将您的属性设置为私有,然后让您的公共 get/set 方法返回或更改这些属性。只是将来需要注意的事情。

希望对您有所帮助!如果您有其他问题或需要澄清,请随时给我发消息。

【讨论】:

    【解决方案2】:

    您需要为要从其中返回值的每个函数设置一个返回类型。 例如:

    public int getAge()
    {
        return Age;
    }
    public int getWeight()
    {
        return Weight;
    }
    public int getHeight()
    {
        return Height;
    }
    

    【讨论】:

      【解决方案3】:

      您需要在每个方法修饰符之后指定一个返回值。
      例如,
      public int getAge() { return age;}

      【讨论】:

        猜你喜欢
        • 2014-04-23
        • 2023-03-21
        • 2013-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多