输入无效仍会更新总计

时间:2015-06-18 22:27:50

标签: java

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

    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");
     }                        
  }

2 个答案:

答案 0 :(得分:3)

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

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

此外,我发现它有点误导,在负面中命名一个布尔值。如果一个名为'invalid'的布尔值为true,则会产生一个问题,“真实表示有效还是无效?”

我会将布尔值命名为“有效”。

答案 1 :(得分:2)

您的程序没有说负数是无效输入的任何地方。 - =和+ =运算符只适用于负数。

[编辑] 假设您选择“离开”并提供numLeaving = -65 tehn总人数将为0 - ( - 65)= 65.您将输入以下代码的if块而不是检查负输入的else块。

    if (totalPeople > MAX_PEOPLE) {
       invalid = false;
       totalPeople = totalPeople - numEntering;
       JOptionPane.showMessageDialog(null,"Capacity exceeded\n" + "Total people = " + totalPeople);
    } 
    else if (numLeaving < MIN_PEOPLE || numEntering < MIN_PEOPLE || totalPeople < MIN_PEOPLE) { 
       JOptionPane.showMessageDialog(null,"Invalid data"); 
    } 
    else {
       JOptionPane.showMessageDialog(null,"Total people = " + totalPeople);              
    }