[英]Reading multiple lines from console in java
我需要從控制台獲取多行輸入,這將是我的類問題的整數。 到目前為止,我一直在使用掃描儀,但沒有解決方案。 輸入包含n條線。 輸入以整數開頭,然后是一系列整數,然后重復多次。 當用戶輸入0時即停止輸入。
例如
輸入:
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));
您可以使用scan.nextLine()獲取每一行,然后通過在空格字符上將其拆分來從該行中解析出整數。
您需要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
}
在這里,出於優雅(IMHO),內部循環是通過流實現的。
正如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())));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.