2012-11-20 20 views
1

我正在尋找解決一個編碼問題,這需要我輸入任意數量的一次整數的輸入。我正在使用ArrayList來存儲這些值。輸入任意次數


The input will contain several test cases (not more than 10). Each 
testcase is a single line with a number n, 0 <= n <= 1 000 000 000. 
It is the number written on your coin. 

例如

Input: 

12 
2 
3 
6 
16 
17 

我試圖把輸入Java中:

List<Integer> list = new ArrayList<Integer>(); 
Scanner inp = new Scanner(System.in); 
while(inp.hasNext()){ 
    list.add(inp.nextInt()); 
    } 

但是,當我嘗試打印列表中的元素以檢查是否正確輸入了輸入時,我沒有得到任何輸出。在C對應的正確的代碼是這樣的:


unsigned long n; 
while(scanf("%lu",&n)>0) 
{ 
    printf("%lu\n",functionName(n)); 
} 

請幫我解決這件事情與Java。


(PS:我不能夠在Java中提交因爲這個解決方案)

回答

0

你能不能做這樣的事情:

List<Integer> list = new ArrayList<Integer>(); 
    Scanner inp = new Scanner(System.in); 
    while(inp.hasNextInt()){ 
     list.add(inp.nextInt()); 
    } 

如果像一些其他值字符,循環結束。

+0

它非常相似,我做什麼,但它並不活像ķ。就像我說的,輸入格式是預先指定的,我不能要求用戶輸入一個字符或類似的東西來表示輸入的結束。 – OneMoreError

3

你可以做到這一點!在輸入結束時,您可以指定一些字符或字符串終止符。

代碼:

List<Integer> list = new ArrayList<Integer>(); 
Scanner inp = new Scanner(System.in); 
while(inp.hasNextInt()) 
{ 
    list.add(inp.nextInt()); 
} 
System.out.println("list contains"); 
for(Integer i : list) 
{ 
    System.out.println(i); 
} 

樣本輸入:

10 
20 
30 
40 
53 
exit 

輸出:

list contains 
10 
20 
30 
40 
53