简体   繁体   中英

Why does scanner object skipping String input nextLine() after use of nextInt() functions inside for loops?

The problem occurred after entering integer value on the first iteration, the program supposed to stop on the 2nd iteration for String input, but skipped the string and wait on nextInt() input.

The code looks like this:

        for (int i=0; i<id.length; i++){
        System.out.println("Enter customer " + (i+1) + " name: " );
        name[i] = input.nextLine(); //this is skipped on the 2nd iteration

        System.out.println("Enter customer " + (i+1) + " ID: ");
        id[i] = input.nextInt();
        }

Explanation

input.nextInt() only consumes the integer, but not the newline character at the end of the line. When the execution gets to input.nextLine() on the next iteration of the loop, the newline character from last iteration is immediately consumed and put on name[i].

Solution

You can solve this by adding another input.nextLine() after reading the integer with input.nextInt() . Demonstration below:

for (int i=0; i<id.length; i++){
    ...
    id[i] = input.nextInt();
    input.nextLine(); // consume spare newline character
}

Your lines might look this this:

1 \n
2 \n
3 \n

If you start by reading an int , then your "pointer" moves to the place between 1 and \n . If you then go to new line, your pointer moves past \n and down to the next line. Whenever you read an int, you don't read the whole row. To fix this, just add input.nextLine(); everytime you read an int . Or you could read the line and then cast it to an int like this: Integer.valueOf(input.nextLine());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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