2016-07-07 55 views
0

我試圖運行的循環將初始化,但不會在第一個循環後繼續運行。由於我知道問題出在哪裏,我拿出了大部分代碼來修復這個循環。我做了第二個選擇後,循環將不會運行。感謝您的任何幫助。while循環初始化但不循環java

public static void main(String[] args) 
{ 
    String number; // enter number   
    int stringLength = 0;  
    String selection = "y" ; 
    // Create a Scanner object to read input. 
    Scanner keyboard = new Scanner(System.in); 

// PrintWriter outputFile = new PrintWriter("outDataFile.txt"); 
// outputFile.close(); 

    while (selection == "y") 
    { 

    // Get the user's number. 
    System.out.print("Write your number "); 
    number = keyboard.nextLine(); 


    System.out.print("y/Y to continue, any else to exit"); 
    selection = keyboard.nextLine(); 


    } 

} 
+0

使用'=='來比較字符串並不符合您在Java中所期望的。參見[如何比較Java中的字符串?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java)。 – Jesper

回答

1

您應該使用equals,而不是==的字符串作爲==僅比較引用而不是對象中的數據,所以:

while (selection.equalsIgnoreCase("y")) 

忽略大小寫,因爲您在郵件中有"y/Y to continue, any else to exit"

+0

和更好的'equalsIgnoreCase()' – NwDev

+0

@NwDx正確的,加上 –

2

修改您的條件:

while ("y".equalsIgnoreCase(selection.trim())) 

它的更好,所以你比較實際的字,而不是他對象標識與equals比較字符串。修剪會刪除錯誤添加

而且任何空白,這是更好地與左邊的不斷"y"比較,以避免NullPointerException

此外,如在對方的回答進行了說明,該equalsIgnoreCase()也很重要。

+1

Scanner.nextLine()應該永遠不會返回null,但你說得對,應該比較常數是更好的方法。 – NwDev