Java 错误 - "invalid method declaration; return type required"

标签 java

我们现在正在学习如何在 Java 中使用多个类,并且有一个项目要求创建一个包含 radius 的类 Circle code> 和 diameter,然后从主类中引用它来查找直径。此代码继续收到错误(标题中提到)

public class Circle
{
    public CircleR(double r)
    {
        radius = r;
    }
    public diameter()
    {
        double d = radius * 2;
        return d;
    }
}

感谢您的帮助,-AJ

更新 1: 好的,但我不应该将第三行 public CircleR(double r) 声明为 double,对吧?在我正在学习的书中,示例没有这样做。

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) 有何不同>?不管什么原因,书上的代码没有给出错误,但是我的说那里有错误。

最佳答案

As you can see, the code public Circle(double r).... how is that different from what I did in mine with public CircleR(double r)? For whatever reason, no error is given in the code from the book, however mine says there is an error there.

在定义类的构造函数时,它们应该与类同名。 于是下面的代码

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。

所以你的新类(class)应该是

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。

引用这个article关于构造函数。

HTH.

关于Java 错误 - "invalid method declaration; return type required",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7451707/

相关文章:

java - Android AES 加密/解密结果不正确

java - 从 java 将参数传递给 c 代码

java - JAXB 类型已定义

java - java中平台无关的声音格式是什么

java - 为什么在达到 InitiatingHeapOccupancyPercent 时 G1 不开始标记周期?

java - Python 中的 OOP 范式

java - 数据驱动规则引擎 - Drools

java - 我的列表中的 Grails .size().toString() 不起作用

java - 无法将 bean @Autowire 到 Controller 中 - NoSuchBeanDefinitionException

java - Maven 版本插件,在多模块项目中递归更新父级