gpt4 book ai didi

java - 无效输入仍会更新总数

转载 作者:行者123 更新时间:2023-12-01 16:57:21 25 4
gpt4 key购买 nike

[编辑]似乎将这段代码移到其他地方可以解决我的问题,但我无法弄清楚在哪里..

    if (numLeaving < MIN_PEOPLE || numEntering < MIN_PEOPLE || totalPeople < MIN_PEOPLE) { 
JOptionPane.showMessageDialog(null,"Invalid data");
}

有人可以解释为什么当我输入无效值(例如负数)时我的“总人数”仍然会更新吗?另外,如果用户输入无效输入,为什么总人数仍会被打印出来?

  final int MAX_PEOPLE = 65; 
final int MIN_PEOPLE = 0;
int totalPeople = 0;
int numLeaving = 0;
int numEntering = 0;
boolean invalid = true;
while (invalid) {
String question = JOptionPane.showInputDialog("leaving or entering?");
try {
// Decrease the total if people are leaving
if (question.equalsIgnoreCase("leaving")) {
numLeaving = Integer.parseInt(JOptionPane.showInputDialog("number leaving:"));
totalPeople -= numLeaving;
}
// Increase the total if people are entering
else if (question.equalsIgnoreCase("entering")) {
numEntering = Integer.parseInt(JOptionPane.showInputDialog("number entering:"));
totalPeople += numEntering;
}
else {
JOptionPane.showMessageDialog(null,"'leaving' or 'entering' only");
}
// Prints out current total before capacity is exceeded
if (totalPeople > MAX_PEOPLE) {
invalid = false;
totalPeople = totalPeople - numEntering;
JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + totalPeople);
}
else {
JOptionPane.showMessageDialog(null,"Total people = " + totalPeople);
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"numbers only");
}
}

最佳答案

“totalPeople”仍在更新的原因是您没有在循环开始时检查它是否是有效输入。如果我是你,我会在 while 循环的开头添加以下代码:

if(totalPeople < 0){
invalid = false;
break;
}

此外,我发现将 boolean 值命名为负数有点误导。如果一个名为“invalid”的 boolean 值为 true,就会产生一个问题:“true 代表有效还是无效?”

我会将 boolean 值命名为“valid”。

关于java - 无效输入仍会更新总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30926890/

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