2016-12-14 36 views
0

私はarraylistに文字列を追加するための簡単なコードを持っています。ユーザーが空白の入力を与えたとき(または基本的に2回クリックするとき)にwhileループを終了する必要があります。ここでEnterキーを押すと終了します(Java)

コードです:あなたは最後のオプションを使用し、スペースまたは空白行または10個のスペースを渡して、ユーザに終了したい場合は

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("")) 
関連する問題