【问题标题】:Syntax Errors in the test class/client code测试类/客户端代码中的语法错误
【发布时间】:2019-07-17 04:43:50
【问题描述】:

我正在尝试创建一个具有重载构造函数的 Rectangle 类。第一个构造函数不需要参数。第二个有两个参数,一个是长度,第二个是宽度。成员变量存储矩形的长度和宽度,成员方法分配和检索矩形的长度和宽度并返回矩形的面积和周长。需要通过编写适当的客户端代码来测试该类。问题是代码中有很多我不知道如何解决的语法错误。

公共类矩形{

public static void main(String[] args) {
          private int length;
          private int width;

          Rectangle(){
            this.length=1; // assuming default length=1
            this.width=1; // assuming default width=1
          }

          Rectangle(int length, int width){
            this.length=length; 
            this.width=width; 
          }

        int area(){
           return length*width;
        }
        int perimeter(){
          return 2*(length+width);
        }
        }


        // test class

        public class TestRectangle{
            public static void main(String args[]){
                Rectangle r1= new Rectangle();
                System.out.println("Area of r1: "+ r1.area());
                Rectangle r2= new Rectangle(2,3);
                System.out.println("Perimetr of r2: "+ r2.perimeter());
            }
        }

}

}

【问题讨论】:

  • 你为什么要在 main 方法中重新定义类 Rectangle?

标签: java class syntax constructor


【解决方案1】:

你真的不需要两个类,但是你不能在这样的方法中定义一个类。

从一个类开始,然后如果你想把它们分开,你需要两个文件

public class Rectangle {
    private int length;
    private int width;

    Rectangle() {
        this.length = 1; // assuming default length=1
        this.width = 1; // assuming default width=1
    }

    Rectangle(int length, int width) {
        this.length = length;
        this.width = width;
    }

    int area() {
        return length * width;
    }

    int perimeter() {
        return 2 * (length + width);
    }

    public static void main(String args[]) {
        Rectangle r1 = new Rectangle();
        System.out.println("Area of r1: " + r1.area());
        Rectangle r2 = new Rectangle(2, 3);
        System.out.println("Perimetr of r2: " + r2.perimeter());
    }
}

编写一个主要方法并不是正确的测试。为此,您应该至少使用 Junit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 2015-12-18
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    相关资源
    最近更新 更多