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));
2
  • 1
    You are running into this skipping issue Commented Nov 22, 2016 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() Commented Nov 22, 2016 at 23:46

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.