我正在阅读Java教程,但遇到了麻烦。
当我执行wall.setHeight(-1.5)
它返回我4而不是0的高度。
谁能告诉我我的语法有什么问题吗?
public class Wall {
private double width;
private double height;
public Wall(){
System.out.println("Empty");
}
public Wall(double width, double height) {
this.width = width;
this.height = height;
System.out.println("width=" + this.width + "height=" + this.height);
}
public void setWidth(double width) {
if((this.width)<0){
this.width = 0.00;
}
}
public void setHeight(double height) {
System.out.println("got here ");
if((this.height)<0){
this.height = 0.00;
}
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
public double getArea(){
return (this.width) * (this.height);
}
}
public class main {
public static void main(String[] args) {
Wall wall = new Wall(5,4);
System.out.println("area= " + wall.getArea());
wall.setHeight(-1.5);
System.out.println(wall.getHeight());
System.out.println("width= " + wall.getWidth());
System.out.println("height= " + wall.getHeight());
System.out.println("area= " + wall.getArea());**
}
}
最佳答案
要使用输入“ -1.5”修复您的setHeight()
方法,请执行以下操作:
public void setHeight(double height) {
System.out.println("got here ");
if (height < 0) { // use "height" instead of "this.height"
this.height = 0.00;
}
}
要对其进行修复,以使其还保存其他零个或更大的值,请执行此操作;
public void setHeight(double height) {
System.out.println("got here ");
if (height < 0) {
this.height = 0.00;
} else {
this.height = height; // set a new value for "this.height" if you didn't zero it out above
}
}
您遇到的困惑是何时使用
height
而不是this.height
。其中一个代表传递到方法中的参数值(height
),另一个代表已经存储在对象上的值(this.height
)。另外,如果您使用IDE(例如IntelliJ),则会看到“ height”变量名称与悬浮文本“从未使用过参数'height'”一起变灰,这将为您提供一个提示,指出您在您的代码。
关于java - setheight()不更改变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59651260/