gpt4 book ai didi

java - setheight() 不改变变量

转载 作者:行者123 更新时间:2023-12-01 06:00:53 29 4
gpt4 key购买 nike

我正在复习 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());**
}
}

最佳答案

要修复您的 setHeight() 方法并输入“-1.5”,请执行以下操作:

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com