gpt4 book ai didi

java - 计数器 : decrease method disregards boolean

转载 作者:行者123 更新时间:2023-12-01 23:23:34 26 4
gpt4 key购买 nike

我正在尝试创建一个计数器,其中包含可以增加和减少的数字。该程序还有一个 boolean 检查:当为 true 时,计数器不能变为负值。该程序似乎运行良好,但我无法获得减少方法(既减一又按输入减少)来获得正确的 boolean 值。它不检查 boolean 值或其他什么?我是 Java 新手,需要帮助了解问题所在。类如下:

public class Counter {

private int value;
private boolean check;

public Counter(int startingValue, boolean check) {
if (this.check = true) {
this.value = startingValue;
if (value < 0) {
value = 0;
}
}
if (this.check = false) {
this.value = startingValue;
}

}

public Counter(int startingValue) {
this.check = false;
this.value = startingValue;
}

public Counter(boolean check) {
this.check = check;
}

public Counter() {
this.value = 0;
this.check = false;
}

public int value() {
return this.value;
}

public void increase() {
value++;
}

public void decrease() {
if (this.check == true) {
this.value--;
if (value < 0) {
value = 0;
}
} else if (this.check == false) {
this.value--;
}
}

public void increase(int IncreaseAmount) {
if (IncreaseAmount >= 0) {
this.value = value + IncreaseAmount;
}
}

public void decrease(int DecreaseAmount) {
if (DecreaseAmount >= 0) {
this.value = value - DecreaseAmount;
}
if (check == true && value < 0) {
value = 0;
}
}
}

现在,如果我要使用此类执行主程序,例如:

Counter count = new Counter (2, true);
count.decrease();
count.decrease();
count.decrease();

我希望我的程序不要出现负数,因为 boolean 检查是正确的。但它确实会变成-1。这是为什么?

最佳答案

您未能将全局变量 check 设置为 false。您还使用 = 而不是 ==:

用途:

public Counter(int startingValue, boolean check) {
this.check = check;
if (check == true) {
value = startingValue;
if (value < 0) {
value = 0;
}
}
else {
value = startingValue;
}
}

关于java - 计数器 : decrease method disregards boolean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20330171/

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