gpt4 book ai didi

java - 输出打印一个小于最终 int 的值

转载 作者:行者123 更新时间:2023-11-30 08:07:18 25 4
gpt4 key购买 nike

当总人数小于 0 时,如何让该程序输出“无效数据”而不是“总人数”?

另外,为什么当我在“输入人数”时输入格式问题时,它会打印“总人数”,然后让我再次输入“离开人数”。我怎样才能让它提示我输入“数字输入”直到有效?

 final int MAX_PEOPLE = 65; 
final int MIN_PEOPLE = 0;
int totalPeople = 0;

while (totalPeople <= MAX_PEOPLE) {
try {
int numLeaving = Integer.parseInt(JOptionPane.showInputDialog("number leaving:"));
int numEntering = Integer.parseInt(JOptionPane.showInputDialog("number entering:"));
if (numLeaving < MIN_PEOPLE || numEntering < MIN_PEOPLE) {
JOptionPane.showMessageDialog(null,"Invalid data");
}
else {
totalPeople = (totalPeople + numEntering) - numLeaving;
}
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Enter numbers only");
}
if (totalPeople > MAX_PEOPLE) {
JOptionPane.showMessageDialog(null,"Capacity exceeded");
}
else {
JOptionPane.showMessageDialog(null,"Total people");
}
}

最佳答案

我发现您的程序有 2 个问题

  1. 如果在“号码输入”或“号码离开”中输入无效输入,则应分别提示返回“号码输入”或“号码离开”。

  2. 它应该输出“无效数据”是变量 totalPeople <0.

您可以通过创建 while 来解决第一个问题循环 numLeavingnumEntering并检查无效输入,直到收到正确的输入,如下所示:

对于numLeaving :

    int numLeaving = -1;
while(numLeaving < MIN_PEOPLE){
try{
numLeaving = Integer.parseInt(JOptionPane.showInputDialog("number leaving:"));
if(numLeaving < MIN_PEOPLE){
JOptionPane.showMessageDialog(null,"Invalid data");
}
}catch(NumberFormatException ex){
JOptionPane.showMessageDialog(null,"Enter numbers only");
}
}

对于numEntering :

    int numEntering = -1;
while(numEntering < MIN_PEOPLE){
try{
numEntering = Integer.parseInt(JOptionPane.showInputDialog("number entering:"));
if(numEntering < MIN_PEOPLE){
JOptionPane.showMessageDialog(null,"Invalid data");
}
}catch(NumberFormatException ex){
JOptionPane.showMessageDialog(null,"Enter numbers only");
}
}

现在上面的代码消除了检查 (numLeaving < MIN_PEOPLE || numEntering < MIN_PEOPLE) 的要求因为它已得到照顾。所以你可以简单地计算totalPeople并检查它是否小于 0 并执行适当的操作,如下所示:

    totalPeople = (totalPeople + numEntering) - numLeaving;
if (totalPeople < MIN_PEOPLE) {
JOptionPane.showMessageDialog(null,"Invalid data");
totalPeople = 0;
continue;
}

我觉得这些建议可以解决您的问题。

关于java - 输出打印一个小于最终 int 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30915889/

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