2013-04-11 71 views
1

以下是我的Java代碼。如果用戶輸入的數字不等於1,則將再次調用方法getInput()Java計數器無法正常工作

public void getInput(){ 
int i=0; 
    while(i<=4){ 
     result[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter Result (1 = pass, 2 = fail)")); 
     int res = result[i]; 
     if(res!=1){ 
      JOptionPane.showMessageDialog(null,"Wrong input, please try again!"); 
      System.out.println("Wrong Input:" + res); 
      getInput(); 
     } 
     System.out.println("count:"+i); 
     i=i+1; 
    } 
} 

下面是結果由代碼產生

  • 計數:0 < - 啓動從計數0
  • 數:1
  • 錯誤輸入:2 < - 輸入錯誤輸入和呼叫再次使用方法getInput()
  • 計數:0 < - 啓動從計數0
  • 數:1
  • 計數:2
  • 計數:3
  • 計數:4
  • 計數:2 < - 再次從2
  • 啓動
  • 計數:3
  • 計數:4

問題是計數器無法正常工作。有人可以幫助我解決這個問題,爲什麼會發生這種情況?

回答

1

從內部調用getInput()開始遞歸。遞歸方法調用完成後,執行將在調用站點恢復,並且(假設沒有副作用)具有與遞歸調用之前相同的狀態。

因此,如果用戶輸入2調用getInput()遞歸,一旦這種「內部」成功執行(即用戶輸入1分四次),「內部」 getInput()回報和與外一個恢復確切相同像以前一樣(你的計數變量是在本地聲明的!)。

我會建議不要在此處使用遞歸,但一個簡單的if/else結構和改變變量i保持狀態:

while (i <= 4) { 
    // input code here 
    if (res != 1) { 
     // fail message for user here 
     i = 0; 
    } else { 
     // success message for user here 
     i++; 
    } 
} 

注意,此方法可能妨礙用戶,選擇取消執行應該被添加(:

+0

數:0 輸入錯誤: 數:0 數:1 數:2 數:3 計數:4 count:0 count:1 count:2 count:3 count:4 - 這是我在實現上述代碼時得到的結果。 while循環運行兩次。 – 2013-04-11 10:31:09

+0

您是否在if條件中刪除了'getInput()'調用?它看起來像你還在遞歸到你的方法。 – Pyranja 2013-04-11 10:35:09

+0

謝謝Prynja!刪除遞歸調用修復了這個問題。 :) – 2013-04-11 10:49:33

4

每次調用getInput()設置i = 0的方法時,嘗試通過計數器作爲方法參數:

public void getInput(int i){ 
    while(i<=4){ 
     result[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter Result (1 = pass, 2 = fail)")); 
     int res = result[i]; 
     if(res!=1){ 
      JOptionPane.showMessageDialog(null,"Wrong input, please try again!"); 
      System.out.println("Wrong Input:" + res); 
      getInput(); 
     } 
     System.out.println("count:"+i); 
     i=i+1; 
    } 
} 

我不會用遞歸調用用於此目的,何樂而不爲呢是這樣的:

public void getInput(){  
    while(i<=4) && ((res = Integer.parseInt(JOptionPane.showInputDialog("Enter Result (1 = pass, 2 = fail)"))) != 1){   
     JOptionPane.showMessageDialog(null,"Wrong input, please try again!"); 
     System.out.println("Wrong Input: " + res);   
     i = i + 1; 
    } 
    System.out.println("count:" + i);   
    } 
} 
+0

我試過這個,它並沒有解決問題:('getInput(0);'傳遞參數值0到if條件中的方法 – 2013-04-11 10:25:14

+0

你需要在調用之前增加i功能recursevley – CloudyMarble 2013-04-11 10:35:53

+0

我沒有給你,你能編輯代碼並顯示嗎? – 2013-04-11 10:41:33