2016-11-22 150 views
0

我需要獲取多行輸入,這些輸入將來自控制檯的整數,用於處理類問題。到目前爲止,我一直在使用掃描儀,但我沒有解決方案。輸入包括n線的數量。輸入以一個整數後跟一串整數開始,這個重複很多次。當用戶輸入0即輸入停止時。在java中從控制檯讀取多行

例如

輸入:

3 
3 2 1 
4 
4 2 1 3 
0 

那麼,如何可以讀此一系列的線和可能的存儲每行使用掃描儀對象的陣列的元件?到目前爲止,我曾嘗試:

Scanner scan = new Scanner(System.in); 
    //while(scan.nextInt() != 0) 
    int counter = 0; 
    String[] input = new String[10]; 

    while(scan.nextInt() != 0) 
    { 
     input[counter] = scan.nextLine(); 
     counter++; 
    } 
    System.out.println(Arrays.toString(input)); 
+1

您正在運行到這個[跳過問題](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) –

+0

你需要2個循環:一個外部循環讀取數量,和一個內部循環讀取許多整數。在兩個循環結束時,你需要'readLine()' – Bohemian

回答

1

你可以使用scan.nextLine()來獲取每一行,然後通過拆分它的空格字符解析出從線路的整數。

1

您需要2個循環:讀取數量的外部循環以及讀取許多整數的內部循環。在兩個循環的末尾,您需要readLine()

Scanner scan = new Scanner(System.in); 

for (int counter = scan.nextInt(); counter > 0; counter = scan.nextInt()) { 
    scan.readLine(); // clears the newline from the input buffer after reading "counter" 
    int[] input = IntStream.generate(scan::nextInt).limit(counter).toArray(); 
    scan.readLine(); // clears the newline from the input buffer after reading the ints 
    System.out.println(Arrays.toString(input)); // do what you want with the array 
} 

這裏爲優雅(恕我直言)內循環是用流實現的。

0

由於mWhitley說只是用String#split拆就空格字符的輸入線

這將讓每行的整數轉爲列表,然後打印

Scanner scan = new Scanner(System.in); 
ArrayList integers = new ArrayList(); 

while (!scan.nextLine().equals("0")) { 
    for (String n : scan.nextLine().split(" ")) { 
     integers.add(Integer.valueOf(n)); 
    } 
} 

System.out.println((Arrays.toString(integers.toArray())));