2017-10-10 116 views
0
public class ex1 { 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    System.out.println("Please enter a series of strings each followed by the enter key. When you'd like to end thr program simply type 'quit': \n"); 
    Scanner scan = new Scanner(System.in); 

    ArrayList<String> inputList = new ArrayList<String>(); // creates a list to store user input 

    String input = scan.nextLine(); //takes the scanner input 
    while(input != "quit") { //makes sure its not equal to quit 
     //System.out.println(input); 
     inputList.add(input); 
     input = scan.nextLine(); 
    } 
    scan.close();  
    System.out.println("The number of strings enetered was: " + inputList.size()); 
    System.out.println("The strings you entered were as follows"); 
    for (String i: inputList) { 
     System.out.println(i); 

    } 

}} While循環用掃描儀永不滿足的條件

我試圖使用上述代碼中使用回車鍵採取了一系列的輸入來自用戶,如果他們輸入quit我結束該程序。但條件是永不滿足和while循環永遠不會結束,我不明白爲什麼

回答

0
while(!input.equals("quit")) { //makes sure its not equal to quit 
     //System.out.println(input); 
     inputList.add(input); 
     input = scan.nextLine(); 
    } 

您應該使用equals方法如上圖所示比較字符串。 Java提供equals方法來比較兩個字符串的內容。 ==!=運算符用於比較對象的等式。

0

a == b返回true當且僅當,一個指向相同的對象b

equals方法應該被使用,作爲字符串類實現它,這樣,如果一個包含與b相同的字符,它會返回true。

while (!input.equals("quit")) { ... }