Java错误 – “无效的方法声明; 需要返回类型“
我们现在正在学习如何在Java
使用多个类,并且有一个项目要求创建一个包含radius
和diameter
的类Circle
,然后从主类中引用它来查找直径。 此代码继续收到错误(在标题中提到)
public class Circle { public CircleR(double r) { radius = r; } public diameter() { double d = radius * 2; return d; } }
谢谢你的帮助,-AJ
更新1 :好的,但我不应该将第三行public CircleR(double r)
为双,对吧? 在我正在学习的书中,这个例子没有那样做。
public class Circle { //This part is called the constructor and lets us specify the radius of a //particular circle. public Circle(double r) { radius = r; } //This is a method. It performs some action (in this case it calculates the //area of the circle and returns it. public double area( ) //area method { double a = Math.PI * radius * radius; return a; } public double circumference( ) //circumference method { double c = 2 * Math.PI * radius; return c; } public double radius; //This is a State Variable…also called Instance //Field and Data Member. It is available to code // in ALL the methods in this class. }
正如你所看到的,代码public Circle(double r)....
与我在public CircleR(double r)
所做的有什么不同? 无论出于何种原因,书中的代码都没有给出任何错误,但我的说法中存在错误。
正如你所看到的,代码public Circle(double r)….与我在公共CircleR(双r)中所做的有什么不同? 无论出于何种原因,书中的代码都没有给出任何错误,但我的说法中存在错误。
定义类的构造函数时,它们应与其类具有相同的名称。 这样下面的代码
public class Circle { //This part is called the constructor and lets us specify the radius of a //particular circle. public Circle(double r) { radius = r; } .... }
你的代码是正确的
public class Circle { private double radius; public CircleR(double r) { radius = r; } public diameter() { double d = radius * 2; return d; } }
是错误的,因为您的构造函数与其类具有不同的名称。 您可以按照本书中的相同代码更改构造函数
public CircleR(double r)
至
public Circle(double r)
或者(如果你真的想把你的构造函数命名为CircleR)将你的类重命名为CircleR。
所以你的新课应该是
public class CircleR { private double radius; public CircleR(double r) { radius = r; } public double diameter() { double d = radius * 2; return d; } }
我还在你的方法中添加了返回类型double,如Froyo和John B.所指出的那样。
请参阅有关构造函数的文章 。
HTH。
每个方法(构造函数除外)都必须具有返回类型。
public double diameter(){...
你忘了将double声明为返回类型
public double diameter() { double d = radius * 2; return d; }
在main方法中添加类时,我遇到了类似的问题。 原来这不是问题,是我不检查我的拼写。 所以,作为一个菜鸟,我了解到错误的拼写可以而且会搞砸了。 这些post帮助我“看到”了我的错误,现在一切都很好。