我有一个简单的程序,它读取参数参数并输出结果.
例如,如果我使用:
Rectangle r1 = new Rectangle(1.0, 2.0, "RED", false);
System.out.println(r1);
Run Code Online (Sandbox Code Playgroud)
应该返回:
1.0 x 2.0, color: RED
Run Code Online (Sandbox Code Playgroud)
但是如果我输入以下参数怎么办:
Rectangle r8 = new Rectangle();
System.out.println(r8);
Run Code Online (Sandbox Code Playgroud)
当使用上述参数时,我的程序如何输出以下默认结果?
1.0 x 1.0, filled with RED
Run Code Online (Sandbox Code Playgroud)
这是我的代码的一部分:
public class Rectangle extends Shape {
protected double width;
protected double length;
public Rectangle() {
super();
}
public Rectangle(double width, double length) {
super();
this.width = width;
this.length = length;
}
public Rectangle(double width, double length, String color, boolean filled) {
super(color, filled);
this.width = width;
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getArea() {
return (width * length);
}
public double getPerimeter() {
return (2 * (width + length));
}
public String toString() {
if (super.isFilled()) {
return width + " x " + length + ", " + "filled with RED";
} else {
return width + " x " + length + ", " + "color: RED";
}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用if(width = 0){}作为宽度,但因为它是一个原始类型所以它不起作用...任何人都可以告诉我如果使用空参数我怎么能打印出默认值?将不胜感激...谢谢!
Era*_*ran 12
您可以在无参数构造函数中设置默认值:
public Rectangle() {
super("RED", true);
this.width = 1.0;
this.length = 1.0;
}
Run Code Online (Sandbox Code Playgroud)
或者您可以在成员声明中指定默认值:
protected double width = 1.0;
protected double length = 1.0;
Run Code Online (Sandbox Code Playgroud)
并有一个类似的声明与Shape成员的默认值.
或者你可以从无参数构造函数中调用另一个构造函数,如Seelenvirtuose所建议的:
public Rectangle() {
this(1.0, 1.0, "RED", true);
}
Run Code Online (Sandbox Code Playgroud)