I disagree; correct use of nextLine() in a loop will work better. You are also losing the ability to test for the type of the input, or to use Scanner's ability to read multiple tokens per line.
Knute Snortum wrote:Here's my suggestion for how to fix this: use only scanner.nextLine(), and if you want a number, use Integer.parseInt() or Double.parseDouble(). . . .
Trial and error is a very bad way to write code; you need to put more thought into things like lines 7‑9. Can you work out what will go wrong if you enter “Adam Chalkley” as a single line? Or even better, if you enter your middle name as “Adam James Chalkley”?
Adam Chalkley wrote:. . . trial and error . . .
At least if you enter the name all on one line, so you won't have problems with reading empty Strings.
Agree with that part. It can be easy to lose track of what has been read from the keyboard; even more so if the reading is in different methods. But my loop will ensure you really read the remainder of the current line, or the next line which isn't empty, from nextLine(). I think you should reserve nextLine() for when you really want the whole line/whole remainder of the line.
Knute Snortum wrote:. . . if you need to read in a String like "Fred Jones", you have two tokens, because the default separator for tokens is whitespace. The standard solution is to use scanner.nextLine(). The problem arises when you mix scanner.nextInt() and scanner.nextLine(). nextInt() leaves a newline in the buffer and when nextLine() sees this, it thinks you've pressed the <Enter> key, so it assumes you've entered a empty String (""). I used to counsel people to to do a scanner.nextLine() after each scanner.nextInt(), but I find this is not intuitive and it can become easy to lose track. . . ..
Campbell Ritchie wrote:I think we are going to have to agree to differ.
Adam Chalkley wrote:I tried your suggestion but I didn't seem to work it still results in a line being skipped also now when I enter the number 2 to continue the program it throws a NumberFormatException
No, it isn't. I have already told you how you can avoid that exception. At least I think I did. The next() call goes inside the loop to consume and reject the unwanted input. You can find the loop here in a thread about how to write such an input class, or the link I gave you yesterday. You will notice there are slight differences of opinion about Scanner, but I like it as long as you understand what it is doing. Note the loop I showed there:-
Adam Chalkley wrote:. . . the scanner.next() is needed in the catch block . . .
we use scan.next to get the input?
why don't we use scan.nextInt?
You are entering 5 which is read as a valid int; the following token is y which the next line will try to interpret as an int too. Which is isn't.
Adam Chalkley wrote:. . . when I enter 5 y I get an exception . . .