繁体   English   中英

在Java中从控制台读取多行

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM