2014-10-18 22 views
0
System.out.print("Enter some stuff:"); 
    while (input.hasNext()){ 
     System.out.print(input.next()+ " "); 
    } 

只要運行,它會要求用戶輸入,然後全部打印出來。但是,我想要的是一個循環,它將打印出掃描儀的所有令牌。然後,它意識到沒有更多的令牌,並且循環退出。如何在java中創建一個檢查下一個掃描儀行的循環()

+0

現在還不清楚,請提供一個例子。另外,如果不聲明和初始化所有使用的對象(即'input'),不要給我們一個代碼。 – Dici 2014-10-18 20:29:44

+1

解釋「全部打印出來」和「當沒有更多的令牌時,循環退出」之間的區別。 – RealSkeptic 2014-10-18 20:30:42

+2

對不起,這是一個prude,但我們儘量避免[粗俗語言](http://stackoverflow.com/help/be-nice)... – ajb 2014-10-18 20:32:13

回答

2

好吧,你想讀的標記爲ArrayList,像這樣:

List<String> store = new ArrayList<String>(); 
// read them all in and add them to our list 
while (input.hasNext()) 
    store.add(input.next()); 
// now print them all out 
for (String s: store) 
    System.out.print(s+ " "); 

這樣做是什麼在閱讀它們,並把它們放進ArrayList;然後,閱讀循環會在沒有更多內容需要閱讀時退出。之後,它將全部打印出來。我認爲這是你的想法。如果你想打印出來,而你是在加入他們,那麼你可以

List<String> store = new ArrayList<String>(); 
// read them all in and add them to our list 
while (input.hasNext()) { 
    String s = input.next(); 
    store.add(s); 
    System.out.print(s+ " "); 
} 
for (String s: store) { 
    // do whatever you like with them 
} 
+1

+1我的字面意思是即將發佈相同的確切答案。慢速打字的痛苦@ chiastic-security – Tetramputechture 2014-10-18 20:33:57

+1

@Tetramputechture這就是讓我在平板電腦上寫作SO答案時多多少少放棄的原因!所以減慢它通常是多餘的,當我完成... – 2014-10-18 20:35:33

+0

但是,如果我想要存儲的值是不同的數據類型呢?假設我希望能夠區分整數和某些可能輸入的關鍵字。並拒絕所有其他人 – 2014-10-18 20:37:17

0

不要僅僅複製,試着去了解隊友:

import java.io.*; 
import java.util.StringTokenizer; 

public class PrintStuff { 

public static void main (String[] args) { 
    System.out.print("Enter some shit seperated by space:"); 
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    String str=""; 
    try { 
     str = br.readLine(); 
    } catch (IOException ioe) { 
     System.out.println("IO error trying to read bitch!"); 
    } 

    StringTokenizer st = new StringTokenizer(str); 

    while (st.hasMoreElements()) { 
     System.out.println(st.nextElement()); 
    } 
} 

}