2016-12-14 153 views
0

我有添加字符串到arraylist的簡單代碼。我需要終止我的while循環時,用戶提供一個空白輸入(或點擊輸入兩次基本上)。按回車鍵退出(Java)

下面是代碼:

static ArrayList<String> names = new ArrayList(); 

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    System.out.println("Enter name:"); 

    String name = sc.nextLine(); 
    while (!name.equals(" ")) { // ? 

     names.add(name); 
     name = sc.nextLine(); 
     if (names.contains(name)) { 
      System.out.println(name + " already exists!"); 
      name = sc.nextLine(); 
     } 

    } 
    System.out.println(names); 

} 
+3

' 「 」'是不一樣的'「」'! – ParkerHalo

回答

3
while (!name.equals(" ")) //string containing single space 
while (!name.equals("")) //empty string 
while (!name.trim().equals("")) //string empty or with only whitespaces 

所以,如果你想在用戶通過空格或空行或十個空格終止,使用最後一個選項。

2

變化while條件如下:

while (!name.trim().equals(""))