2013-04-18 83 views
-3

这是我的第一类称为类圆:为什么我的小方法给我一个错误

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 
+1

“_it给了我一个错误_”;那是什么错误? – mshsayem

+0

'c3'没有类型。 – alex

+0

开始使用eclipse – smerny

回答

2

smaller方法应该有一个返回类型。另外this关键字不能用于static方法。即该方法将无法访问Circle的实例。鉴于这是有意义的是什么方法名smaller暗示 - 它的Circle当前实例与另一个传入比较

public Circle smaller(circle other) { 
    if (this.area > other.area) { 
    return other; 
    } else { 
    return this; 
    } 
} 

要使用:

Circle smallerCircle = circle1.smaller(circle2); 

Aside:的Java命名惯例表明,类名开始一个大写给字母Circle

c3 = c1.area(c2); 

你需要做的GeArea()调用之前,你可以使用类的面积领域:当你操作

+0

+1删除我的答案,因为你的答案更完整。 –

+0

如果他复制粘贴虽然,该方法会抛出一个错误,因为他的课目前被宣布为“圆”而不是“圆”。您的返回类型与您的参数不同。 –

+1

是的,但我没有解释,在最后,并希望鼓励使用Java命名约定:) – Reimeus

1

区是未分配。

因此,例如:

circle circle1 = new circle(4,9,6); 

circle circle2 = new circle(4,7,6); 
circle2.area = c1.getArea(); 

这是假设你想分配C3 VAR到已实例为一个圆。

0

你根本都忘了一个右括号

if (this.area > other.area) 
{ 
    return other; 
} //You forgot this brace and confused the compiler 
else 
{ 
    return this; 
} 
+1

该方法的问题比支架更多。 –

相关问题