Java error - “invalid method declaration; return type required”

前端 未结 4 1573
难免孤独
难免孤独 2020-12-06 12:42

We are learning how to use multiple classes in Java now, and there is a project asking about creating a class Circle which will contain a rad

相关标签:
4条回答
  • 2020-12-06 13:02

    Every method (other than a constructor) must have a return type.

    public double diameter(){...
    
    0 讨论(0)
  • 2020-12-06 13:03

    You forgot to declare double as a return type

    public double diameter()
    {
        double d = radius * 2;
        return d;
    }
    
    0 讨论(0)
  • 2020-12-06 13:10

    I had a similar issue when adding a class to the main method. Turns out it wasn't an issue, it was me not checking my spelling. So, as a noob, I learned that mis-spelling can and will mess things up. These posts helped me "see" my mistake and all is good now.

    0 讨论(0)
  • 2020-12-06 13:16

    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.

    When defining constructors of a class, they should have the same name as its class. Thus the following code

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

    is correct while your code

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

    is wrong because your constructor has different name from its class. You could either follow the same code from the book and change your constructor from

    public CircleR(double r) 
    

    to

    public Circle(double r)
    

    or (if you really wanted to name your constructor as CircleR) rename your class to CircleR.

    So your new class should be

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

    I also added the return type double in your method as pointed out by Froyo and John B.

    Refer to this article about constructors.

    HTH.

    0 讨论(0)
提交回复
热议问题