2013-02-18 112 views
-2

嗨,大家好我嘗試退出與此位的代碼的循環,但之前結束它仍然打印出來,我不想行:Java循環還沒有結束正確

do { 
     System.out.println("Would you like to change one of the numbers (y/n)?"); 
     choice = kb.next().charAt(0); 
     System.out.println("Please enter the index of the number you want to change:"); 
     indexChange = kb.nextInt(); 
     System.out.println("Please enter the number you want to change:"); 
     changedIndex = kb.nextInt(); 
     elements[indexChange - 1] = changedIndex; 
     for (int i = 0; i < elements.length; i++) 
      System.out.println(index[i] + elements[i]); 

    } while (choice != 'n'); 

這兩條線還是打印出來在循環結束之前:「請輸入您要更改的號碼:」&「請輸入您要更改的號碼:」。你們能協助解決這個問題嗎?

+1

使用調試器! – 2013-02-18 22:38:13

+1

這是一個邏輯問題,調試器不會有太大的幫助。鉛筆和紙張會更快。 – 2013-02-18 22:38:46

+0

@ A - C那麼,像Eclipse和NetBeans中提供的一個好的調試器會向您顯示每行每個變量的實際值。您可以使用此信息在同時測試代碼的同時查找邏輯錯誤。 – 2013-02-18 22:39:56

回答

3

您需要使用您的break循環。在這種情況下,不需要在循環的每次迭代開始或結束時檢查choice,因此您只需使用while (true)即可循環,直至達到break

while (true) { 
     System.out.println("Would you like to change one of the numbers (y/n)?"); 
     choice = kb.next().charAt(0); 
     if (choice == 'n') 
      break; 
     System.out.println("Please enter the index of the number you want to change:"); 
     indexChange = kb.nextInt(); 
     System.out.println("Please enter the number you want to change:"); 
     changedIndex = kb.nextInt(); 
     elements[indexChange - 1] = changedIndex; 
     for (int i = 0; i < elements.length; i++) 
      System.out.println(index[i] + elements[i]); 

    } 

不過要小心。意外寫入無限循環很容易!

+0

這將很好地解釋爲什麼從「do-while」循環到「while」循環的變化。儘管如此,我發現這個解決方案比雙重檢查或雙重檢查break-condition的if-else更好。 – 2013-02-18 22:43:25

1

您需要檢查處理剩餘輸入之前退出條件...

do { 
    System.out.println("Would you like to change one of the numbers (y/n)?"); 
    choice = kb.next().charAt(0); 
    if (choice != 'n' && choice != 'N') { 
     System.out.println("Please enter the index of the number you want to change:"); 
     indexChange = kb.nextInt(); 
     System.out.println("Please enter the number you want to change:"); 
     changedIndex = kb.nextInt(); 
     elements[indexChange - 1] = changedIndex; 
     for (int i = 0; i < elements.length; i++) { 
      System.out.println(index[i] + elements[i]); 
     } 
    } 

} while (choice != 'n' && choice != 'N'); 

您也應該檢查資金字符...

+0

這工作但結束程序沒有繼續下一階段的代碼,儘管下面的while語句完成了工作。感謝您的提示。 – user1766709 2013-02-18 22:54:10

0

此檢查

while (choice != 'n'); 

只有每do循環迭代出現一次。因此,在你的循環中,你問你是否要更改其中一個數字,然後詢問其他問題,然後檢查他們輸入的值是否爲第一個問題。

您可以使用關鍵字「break」在得到選擇後跳出循環.eg。

if (choice == 'n') 
{ 
    break; 
} 
0

的Try ...

while(!'n'.equals(choice.toLowerCase())){...