Parth
Parth

Reputation: 11

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. 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.

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));

Upvotes: 1

Views: 5406

Answers (3)

cavla
cavla

Reputation: 118

As mWhitley said just use String#split to split the input line on the space character

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())));

Upvotes: 1

Bohemian
Bohemian

Reputation: 425083

You need 2 loops: An outer loop that reads the quantity, and an inner loop that reads that many ints. At the end of both loops you need to 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.

Upvotes: 2

mWhitley
mWhitley

Reputation: 453

You could use scan.nextLine() to get each line and then parse out the integers from the line by splitting it on the space character.

Upvotes: 1

Related Questions