2017-03-08 228 views
0

我试图阅读有关使用while循环预测试条件的一个小程序,它将编译响应和输出数据,但我有一个问题,无论我输入什么输入框告诉我它是无效的。我不确定有什么问题。这是相关的代码。如果语句内while循环错误

import javax.swing.JOptionPane; 

public class SurveySummarization 
{ 
    public static void main(String[] args) 
    { 


     int agree = 0; 
     int disagree = 0; 
     int neutral = 0; 
     int totalVotes = 0; 
     int input; 
     String inputString; 


     inputString = JOptionPane.showInputDialog("Response: \n" + 
        "(1=agree, 2=disagree, 3=no opinion, -1=exit)"); 
     input = Integer.parseInt(inputString); 

     while (input != -1) 
     { 
      if (input == 1) 
      { 
       agree += 1; 
       totalVotes += 1; 
      } 
      if (input == 2) 
      { 
       disagree += 1; 
       totalVotes += 1; 
      } 
      if (input == 3) 
      { 
       neutral += 1; 
       totalVotes += 1; 
      } 
      else { 
       JOptionPane.showMessageDialog(null, "invalid response " 
             + input); 
      } 
     } 


    } 
} 
+5

您是否尝试过调试它?调试是关键,它有助于95%的案例。在每行代码中,inputString的值是什么?另外,请注意,除了3 **以外,您的'else'语句将触发**任何输入值。 –

回答

2

这是因为你没有正确使用else的。如果你看一下你的代码,您的最终if

if (input == 3) 
     { 
      neutral += 1; 
      totalVotes += 1; 
     } 
     else { 
      JOptionPane.showMessageDialog(null, "invalid response " 
            + input); 
     } 

含义,如果输入!= 3,显示了无效的响应。

要解决此问题,请将if更改为else if (input == 2) ...(对于== 3也是如此)。

+2

好吧,所以基本上其他只适用于最终的if语句? – Josh

+2

没错。目前,所有的if都是完全独立的条件,并且计算机正在逐一处理每个条件。 –

+0

你会推荐我用什么来实现这个目标? – Josh

1

正如Steve指出的那样,如果没有正确放置。我想你的意思是把否则,如果 s而不是只是独立的ifs。 import javax.swing.JOptionPane;

public class SurveySummarization 
{ 
    public static void main(String[] args) 
    { 


     int agree = 0; 
     int disagree = 0; 
     int neutral = 0; 
     int totalVotes = 0; 
     int input; 
     String inputString; 


     inputString = JOptionPane.showInputDialog("Response: \n" + 
       "(1=agree, 2=disagree, 3=no opinion, -1=exit)"); 
     input = Integer.parseInt(inputString); 

     while (input != -1) 
     { 
      if (input == 1) 
      { 
       agree += 1; 
       totalVotes += 1; 
      }else if (input == 2) 
      { 
       disagree += 1; 
       totalVotes += 1; 
      } else if (input == 3) 
      { 
       neutral += 1; 
       totalVotes += 1; 
      } 
      else { 
       JOptionPane.showMessageDialog(null, "invalid response " 
            + input); 
      } 
     } 

    } 
} 
0

既然你知道输入不能在同一时间,你应该如果的其他使用,与第一,如果和其他最终沿等于1 3。当前的代码检查输入是否等于1,如果它很好。那么你检查它是否等于2,但是你的前面的语句没问题,结果输入等于1,因此你不需要检查== 2或== 3.使用if/else if/else链接在一起会链接在一起时只能满足单一条件。一旦你达到满足条件的条件,你可以跳过其余的条件。

if (input == 1) 
{ 
    agree += 1; 
    totalVotes += 1; 
} 
else if (input == 2) 
{ 
    disagree += 1; 
    totalVotes += 1; 
} 
else if (input == 3) 
{ 
    neutral += 1; 
    totalVotes += 1; 
} 
else { 
    JOptionPane.showMessageDialog(null, "invalid response " + input); 
} 
+0

哦,这是正确的!非常感谢! – Josh

+0

不客气@Josh –