2014-03-06 30 views
0

它正在打印一條直線,但我希望它能打印出每一個字的新行。 這就是現在的樣子one, two, three如何更改我的代碼以便每次都在新生產線上打印出來?

while (true) { 
      String word = reader.readLine(); 
      if("end".equalsIgnoreCase(word)) { 
       break; 
      } 
      list.add(word); 
     } 
     System.out.println(list); 
+5

使用循環遍歷列表並使用'System.out.println'在單行中打印每個項目。 –

+0

其ArrayList

+0

@Predict_it儘管如此,每個使用。 :) –

回答

2

這沒有什麼神奇的。在對象上運行println時,它會在該對象上運行.toString()。

while (true) { 
     String word = reader.readLine(); 
     if("end".equalsIgnoreCase(word)) { 
      break; 
     } 
     list.add(word); 
    } 
    for (String word : list) { 
     System.out.println(word); 
    } 
0

通過添加類似:

for (String word : list) { 
    System.out.println(word);} 

這是for-each循環通過列表中的所有元素進行迭代

0

使用循環:

for(String word:list) 
    System.out.println(word); 

或者

for(int i=0; i<list.size(); i++) 
    System.out.println(list.get(i)); 
1

在將單詞添加到列表中後添加system.out.println(單詞)。

while (true) { 
      String word = reader.readLine(); 
      if("end".equalsIgnoreCase(word)) { 
       break; 
      } 
      list.add(word); 
      System.out.println(word); 
     } 
0

不想repwhore,但是這是你會怎麼做,在20天以內的Java 8出來後:

list.forEach(e -> System.out.println(e)); 

「E」在你的字符串與代表特定字符串值值。 我認爲這只是麥汁提及和相當甜蜜的做法。

+0

或'list.forEach(System.out :: println);' –

+0

@鄒鄒更好。 –

相關問題