简体   繁体   English

在Java中从控制台读取多行

[英]Reading multiple lines from console in java

I need to get multiple lines of input which will be integers from the console for my class problem. 我需要从控制台获取多行输入,这将是我的类问题的整数。 So far I have been using scanner but I have no solution. 到目前为止,我一直在使用扫描仪,但没有解决方案。 The input consists of n amount of lines. 输入包含n条线。 The input starts with an integer followed by a line of series of integers, this is repeated many times. 输入以整数开头,然后是一系列整数,然后重复多次。 When the user enters 0 that is when the input stops. 当用户输入0时即停止输入。

For example 例如

Input: 输入:

3
3 2 1
4
4 2 1 3
0

So how can I read this series of lines and possible store each line as a element of an array using a scanner object? 那么,如何读取这一系列行并可能使用扫描程序对象将每一行存储为数组的元素? So far I have tried: 到目前为止,我已经尝试过:

 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()获取每一行,然后通过在空格字符上将其拆分来从该行中解析出整数。

You need 2 loops: An outer loop that reads the quantity, and an inner loop that reads that many ints. 您需要2个循环:一个外部循环读取数量,一个内部循环读取那么多的整数。 At the end of both loops you need to readLine() . 在两个循环的最后,您都需要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
}

Here for elegance (IMHO) the inner loop is implemented with a stream. 在这里,出于优雅(IMHO),内部循环是通过流实现的。

As mWhitley said just use String#split to split the input line on the space character 正如mWhitley所说,只需使用String#split在空格字符上分割输入行

This will keep integers of each line into a List and print it 这会将每行的整数保存到列表中并打印

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