Java 错误 - “无效的方法声明;需要返回类型”

新手上路,请多包涵

我们现在正在学习如何在 Java 中使用多个类,并且有一个项目询问创建一个类 Circle 它将包含一个 radiusdiameter ,然后从主类中引用它以查找直径。此代码继续收到错误(在标题中提到)

 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) 中所做的有什么不同?无论出于何种原因,书中的代码都没有给出错误,但是我说那里有错误。

原文由 Alex G 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

如您所见,代码 public Circle(double r)…. 与我在 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;
  }
 ....
}

是正确的,而您的代码

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;
    }
}

正如 Froyo 和 John B 所指出的,我还在您的方法中添加了返回类型 double。

请参阅 这篇 关于构造函数的文章。

HTH。

原文由 Annie Lagang 发布,翻译遵循 CC BY-SA 3.0 许可协议

每个方法(构造函数除外)都必须具有返回类型。

 public double diameter(){...

原文由 John B 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题