Java 编译错误:缺少方法的返回类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22210262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compiling error: Return type for the method is missing
提问by NeverWalkAlone
public class StoreRatioNumberClass
{
private int num;
private int den;
public RationalNumber() //here
{
num = 0;
den = 1;
}
public RationalNumber(int newNum, int newDen) //and here, but it gives me 3 separate errors for it//
{
num = newNum;
den = newDen;
simplify();
}
private void simplify()
{
int gcd = gcd();
finalNum = num/gcd;
finalDen = den/gcd;
}
private static int gcd(int a, int b)
{
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public double getValue()
{
return (double)num/den;
}
public String toString()
{
return(num + "/" + den);
}
}
My question is how do I solve this compiling issue on lines 7 & 11? This class takes the numerators and denominators entered in the main method class not shown here and simplifies the rational number with the GCD. Also, when I do put in a return type it just comes up with even more errors and warnings so I'm stumped! Thank you for looking and all of your inputs.
我的问题是如何解决第 7 和 11 行的编译问题?该类采用此处未显示的主方法类中输入的分子和分母,并使用 GCD 简化有理数。另外,当我输入返回类型时,它只会出现更多错误和警告,所以我很难过!感谢您的关注和您的所有意见。
采纳答案by donfuxx
You need to use the name of your class in constructor:
您需要在构造函数中使用类的名称:
public StoreRatioNumberClass(int newNum, int newDen) {
//...
otherwise compiler will think you are about to declare a method and is confused about the missing return type obviously
否则编译器会认为您将要声明一个方法并且显然对缺少的返回类型感到困惑
回答by Dathan
Your RationalNumber
methods don't declare a return type. The form you're using is only allowed for constructors. If you change the name of both methods to StoreRatioNumberClass
(i.e., make the method names match the class name to make them valid constructors), your compiler errors should go away.
您的RationalNumber
方法没有声明返回类型。您使用的表单只允许用于构造函数。如果您将两个方法的名称更改为StoreRatioNumberClass
(即,使方法名称与类名称匹配以使其成为有效的构造函数),则编译器错误应该消失。
回答by afsantos
You named your class StoreRatioNumberClass, as in the following class declaration
您将类命名为StoreRatioNumberClass,如下面的类声明
public class StoreRatioNumberClass
I believe you were trying to define constructors for this class, in the lines the compiler complains. Constructors must have the same name as the class, otherwise, they're interpreted as method names (such as your simplify
). However, these false method definitions miss their return type.
我相信您正试图在编译器抱怨的行中为此类定义构造函数。构造函数必须与类同名,否则,它们将被解释为方法名称(例如您的simplify
)。然而,这些错误的方法定义错过了它们的返回类型。
Change
改变
public RationalNumber() //here
to
到
public StoreRatioNumberClass() //here