Java 为什么我的小方法会给我一个错误
这是我的第一节课,叫做“班级圈”:Java 为什么我的小方法会给我一个错误,java,return,this,geometry,Java,Return,This,Geometry,这是我的第一节课,叫做“班级圈”: public class circle { //circle class begins //declaring variables public double circle1; public double circle2; public double circle3; public double Xvalue; public double Yvalue; public double radius; pri
public class circle
{
//circle class begins
//declaring variables
public double circle1;
public double circle2;
public double circle3;
public double Xvalue;
public double Yvalue;
public double radius;
private double area;
//Constructor
public circle(int x,int y,int r)
{//constructor begins
Xvalue = x;
Yvalue = y;
radius = r;
}//constructor ends
//method that gets the area of a circle
public double getArea ()
{//method getArea begins
area = (3.14*(this.radius * this.radius));
return area;
}//getArea ends
public static smaller (circle other)
{
if (this.area > other.area)
{
return other;
else
{
return this;
}
//I'm not sure what to return here. it gives me an error( I want to return a circle)
}
}//class ends
}
这是我的测试人员课程:
public class tester
{//tester begins
public static void main(String args [])
{
circle circle1 = new circle(4,9,4);
circle circle2 = new circle(4,7,6);
c3 = c1.area(c2);
System.out.println(circle1.getArea());
//System.out.println(
}
}//class tester ends
较小的
方法应具有返回类型。另外,this
关键字不能在静态方法中使用。i、 e.该方法将无法访问Circle
的实例。考虑到方法名smaller
的含义,这是有意义的-它将Circle
的当前实例与传入的另一个实例进行比较
public Circle smaller(circle other) {
if (this.area > other.area) {
return other;
} else {
return this;
}
}
使用:
Circle smallerCircle = circle1.smaller(circle2);
旁白:
Java命名约定表明,在执行操作时,类名称以大写字母开头,以给出圆圈区域是未分配的:
c3 = c1.area(c2);
在使用类的area字段之前,需要进行GeArea()调用
例如:
circle circle1 = new circle(4,9,6);
circle circle2 = new circle(4,7,6);
circle2.area = c1.getArea();
这是假设您试图分配给的c3变量已被实例化为一个圆。您只是忘记了右大括号
if (this.area > other.area)
{
return other;
} //You forgot this brace and confused the compiler
else
{
return this;
}
“它给了我一个错误”;那是什么错误?c3
没有类型。如果他复制粘贴了,该方法将抛出错误,因为他的类当前声明为“circle”,而不是“circle”。你的返回类型和你的参数不一样。是的,但我在最后解释了这一点,并希望鼓励使用Java命名约定:)Lol不,我明白了。我只是希望他不要再提出另一个问题,担心他为什么会出错