我们现在正在学习如何在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(双r)....这是怎么回事?与我在public circle(双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方法添加类时遇到了类似的问题。原来这不是问题,是我没有检查我的拼写。所以,作为一个新手,我知道拼写错误会把事情搞砸。这些帖子帮助我"看到"了我的错误,现在一切都好了。