【问题标题】:Need help troubleshooting a Square Class, specifically the code?需要帮助解决 Square 类,特别是代码?
【发布时间】:2017-04-12 03:24:53
【问题描述】:

我正在尝试学习 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; ^

【问题讨论】:

  • 错误在哪里?请发布错误
  • 14 个错误,你不能麻烦发布其中一个?
  • 以下是错误,现在已减少到 4 个。
  • 编译器错误:/tmp/codecheck.XNhW00Z3c8/Square.java:12: 错误:'{' 预期的公共类 Square(double side) ^ /tmp/codecheck.XNhW00Z3c8/Square.java:12 : 错误: ';'预期的公共类 Square(双面)^ /tmp/codecheck.XNhW00Z3c8/Square.java:31:错误:解析时到达文件末尾} ^ /tmp/codecheck.XNhW00Z3c8/Square.java:14:错误:变量边是已经在类 Square private 双面中定义; ^
  • 将错误放入您的问题中,在代码块中。

标签: java class constructor


【解决方案1】:

您实际上是在为类提供参数。在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());
    }
}

【讨论】:

  • 这个参数不就是存放类里面所有代码的吗?
  • 类头中不允许有参数 delete(双面)在类头中谁想到的?
  • 只有在使用泛型时才会在类头中出现类似于参数的任何内容。例如。 public class Node <T>。 @JolandaCarlsen
  • @abcOfJava 它与方法一起使用,所以我认为在类中会是这样。我回答了类似的其他问题并做对了
  • @JolandaCarlsen 请删除它
猜你喜欢
  • 1970-01-01
  • 2021-07-29
  • 2010-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
相关资源
最近更新 更多