【问题标题】:Why is my smaller method giving me an error为什么我的较小方法给了我一个错误
【发布时间】:2013-04-18 00:56:21
【问题描述】:

这是我的第一堂课,叫做课堂圈:

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

【问题讨论】:

  • "它给了我一个错误";这是什么错误?
  • c3 没有类型。

标签: java return this geometry


【解决方案1】:

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

【讨论】:

  • 如果他复制粘贴,该方法将抛出错误,因为他的类当前被声明为“circle”而不是“Circle”。您的返回类型与您的参数不同。
  • 是的,但我确实在最后解释了这一点,并希望鼓励使用 Java 命名约定 :)
  • 大声笑不,我明白了。我只是希望他不要提出另一个担心他为什么会出错的问题。 ;)
【解决方案2】:

进行操作时未分配区域:

 c3 = c1.area(c2);

您需要先调用 GeArea(),然后才能使用该类的 area 字段。

例如:

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

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

这是假设您尝试分配的 c3 var 已被实例化为一个圆圈。

【讨论】:

    【解决方案3】:

    你只是忘记了一个右括号

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      相关资源
      最近更新 更多