Java“矩形”中 类 的驱动程序

Drivers for Classes in Java “Rectangle"

我从未在 Java 中为 driver 使用单独的文件。我习惯于只使用 main 方法。我在 Python 中使用了单独的文件,但 Java 是新的。下面是我对每个 class(“矩形”和“Driver”)的代码,每个都来自不同的文件。

将方法更改为静态更新:不要注意 class 名称或格式的更改……我只是在进行调整,以便它可以与 MyProgrammingLab 一起使用。我仍然必须添加长度和宽度仅介于 0.0 和 20.0 之间的参数(简单 if-else 语句)。

import java.util.Scanner;

public class Driver{

public static void main(String[] args) {

    Scanner input = new Scanner( System.in);

    System.out.print("Enter length of rectangle:");
    double length = input.nextDouble();
    System.out.print("Enter width of rectangle:");
    double width = input.nextDouble();

    Rectangle  Perimeter = new Rectangle(length, width);
    Perimeter.getPerimeter();
    Rectangle  Area = new Rectangle(length, width);
    Area.getArea();

    System.out.printf("Area: %.1f, Perimeter: %.1f",Rectangle.getArea(),Rectangle.getPerimeter());

}

}

最终class矩形{

private static double mLength;
private static double mWidth;

public Rectangle(double length, double width){
    mLength = length;
    mWidth = width;
}   
public double getLength(){
    return mLength;
}

public double getWidth(){
    return mWidth;
}

public static double getArea(){
    double area = mWidth*mLength;
    return area;    
}
public static double getPerimeter(){
    double perimeter = (mWidth*2)+(mLength*2);
    return perimeter;

}

}

如果没有显式编写构造函数,编译器会提供默认构造函数。

但是如果你在 class 中显式编写任何构造函数,那么无论何时调用构造函数,无论是无参数还是有参数,它总是会在 class 中寻找显式定义的构造函数.

而且,这在逻辑上是正确的,因为如果您想阻止创建没有任何数据的对象,添加带参数的构造函数是可行的方法。

因此,要么在 Rectangle 中显式编写无参数构造函数并使用 setter 设置其属性,要么只在方法中使用参数构造函数。


向Rectangle.class添加一个空构造函数:

public Rectangle() {

} 

或者在你的方法中使用参数声明的构造函数

Rectangle rectangle = new Rectangle(length, width);

在您的情况下,您使用的矩形对象有误。 我想你想做的是这个:

Rectangle  rectangle = new Rectangle(length , width );
System.out.printf("Area: %.1f, Perimeter: %.1f",rectangle.getArea() ,rectangle.getPerimeter());

创建具有长度和宽度的 Rectangle 对象更有意义,因此使用重载的 Rectangle 构造函数 传递 lengthwidth 个参数(由用户输入),如下所示:

Rectangle  Perimeter = new Rectangle(length, width);

the constructor Rectangle() is undefined. Can anyone help?

重要的一点是,当你有一个像你的 Rectangle class 中那样的重载构造函数时(没有默认值,即没有编写参数构造函数),你可以不要使用 new Rectangle(); 创建对象,这是因为编译器不会自动为您添加默认构造函数 。我建议查看 here 了解更多详细信息。

另外,如果你想用 lengthwidth 细节打印 Rectangle 对象,你需要 override toString() 方法来自 java.lang.Object方法如下图:

public class Rectangle {

    private double mLength;

    private double mWidth;

    //add your code here as is

    @Override
    public String toString() {
        return "Rectangle [mLength=" + mLength + ", mWidth=" + mWidth + "]";
    }
}