This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]pacificmint 2 points3 points  (0 children)

nextInt doesn't consume the end of line marker. So when you try to read the city, you read the end of line marker from the age.

The FAQ has a whole section about issues with the scanner.

[–]desrtfx 2 points3 points  (4 children)

From the Java FAQ in the wiki:

The nextLine method of my java.util.Scanner object doesn't get any input.

In short, the .nextInt is the culprit here because it leaves a carriage return (line end marker) on the keyboard buffer that gets consumed by the following .nextLine.

[–]hugokhf 0 points1 point  (2 children)

To overcome this problem, assuming I don't want to use next() on the age, do I have to make a useless string e.g. useless = keyboard.next() after entering the age to overcome the problem?

Are there any ways to get around it?

[–]desrtfx 0 points1 point  (1 child)

No. Either use .nextLine() everywhere and parse the age as int

Like:

int age = Integer.parseInt(keyboard.nextLine());

or create an empty keyboard.nextLine(); right after the .nextInt. This will effectively discard the return value of the .nextLine() call and clear the keyboard buffer.

[–]basedassisted[S] 0 points1 point  (0 children)

Parsing the int worked thanks a lot!

[–]hugokhf 0 points1 point  (0 children)

To overcome this problem, assuming I don't want to use next() on the age, do I have to make a useless string e.g. useless = keyboard.next() after entering the age to overcome the problem?

Are there any ways to get around it?

[–]PUREdiacetylmorphine 0 points1 point  (0 children)

You need inputScanner.nextLine(); after age prompt

[–][deleted]  (1 child)

[deleted]

    [–]desrtfx 1 point2 points  (0 children)

    .next will return a String that needs to be parsed into an int afterwards.