需要帮助排除Square类的故障,特别是代码?

时间:2017-04-12 03:24:53

标签: java class constructor

我正在尝试学习java,而且我仍然坚持使用“课程”。部分。他们给了我一个问题,我不确定为什么会出错。

我已经多次阅读了,我不明白为什么会有大约14条错误消息?完全......

这是作业:

  // You are to write the constructor specified for this Square class. The Square class 
  // has an instance variable of type double, side, which is the length of each side of 
  // the square. The javadoc has been provided for you to help you tell what you needs to
  // be done
 // 
 // HINT: Write the constructor for the class Square.
 // The constructor will take in a parameter of the type double
 // and assign that parameter to the instance variable side

这是我的代码:

   public class Square(double side)

  private double side;

  /**
  * Constructor for objects of class Square
  * @param theSide the length of the side of this Square
  */
  public main(double theSide) {
  side = theSide;
  }
  /**
  * Gets the length of a side of this square
  * @return the side of this square
  */
  public double getSide()
  {
   return side;
  }


Compiler error: /tmp/codecheck.XNhW00Z3c8/Square.java:12: error: '{'    expected public class Square(double side) ^ /tmp/codecheck.XNhW00Z3c8/Square.java:12: error: ';' expected public class Square(double side) ^ /tmp/codecheck.XNhW00Z3c8/Square.java:31: error: reached end of file while parsing } ^ /tmp/codecheck.XNhW00Z3c8/Square.java:14: error: variable side is already defined in class Square private double side; ^

1 个答案:

答案 0 :(得分:0)

你实际上是在为班级提供参数。在java类中不应该有参数

看这里

public class Square(double side)

正确的方法

public class Square
{
    private double side;
    public Square(double theSide)
    {
        side=theSide;
    }
    public double getSide()
    {
        return side;
    }


}

另一个班级

public class TestSquare
{

    public static void main(String[] args)
    {
        Square square = new Square(25.00);
        System.out.println("Square sides:"+square.getSide());
    }
}