1

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));
Michael Krause
  • 4,225
  • 1
  • 18
  • 23
Parth
  • 11
  • 1
  • 2
  • 1
    You are running into this [skipping issue](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – OneCricketeer Nov 22 '16 at 23:45
  • 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()` – Bohemian Nov 22 '16 at 23:46

3 Answers3

2

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.

Bohemian
  • 365,064
  • 84
  • 522
  • 658
1

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.

mWhitley
  • 455
  • 8
  • 14
1

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())));
Community
  • 1
  • 1
cavla
  • 98
  • 3
  • 11