2017-03-08 231 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 –