This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Greg Brannon wrote:Please specify the strange behavior. What behavior are you expecting? What behavior is it presenting that you don't expect?
It runs fine until the end of the loop.
I choose too add, then type in 5 and then 6. It now prints;
5+6=11 (which it should). Then it prints the menu again (which it should) but with the "Invalid input" message at the end (which it shouldn't). And it finally prints the menu one last time and the loop is done and I can now type in a new input.
I know how can i fix this but still i have no idea why this code is not working the way it should be..
Joined: Oct 24, 2010
Some of the Scanner methods do not read the end of line (EOL) marker or return so that there is input - the EOL - in the input buffer after nextInt() and others. You'll notice that your program tells you that an invalid input has been made. That's the choice = usrInput.nextLine(); reading the EOL marker and judging it to be an invalid input per the program's logic, then returning to the menu. You can "flush the input buffer" by adding a usrInput.nextLine(); statement at the end of the if/else chain like:
Hope this helps. Keep coding!
Edit: I noticed that my suggested fix is not the perfect solution, because the logic for a choice of "5" is different than the others, causing the program to wait for input before executing the while statement that will terminate the program. Either a better solution (a nextLine() at the end of the other choices) or a different design, a do/while or a while (true) with a System.exit( 0 ) at choice = "5" will provide a complete solution. And there are probably others. Your choice.
I take Vince Stout’s point about always reading a whole line with Scanner. But doesn’t that vitiate the advantage of Scanner, that it can recognise the next token as an int? If you are going to use this Integer.parseInt(), why not use the old-fashioned method with a BufferedReader reading from the keyboard? I would suggest you might want a utility class, which uses a Scanner to read from the keyboard. You would obviously want methods for nextDoubleFromKeyboard, nextBigIntegerFromKeyboard, etc. If you are worried about the line-end problem, you can change each method so as to discard the remainder of the line by putting a nextLine() call at the end of the method. You will of course have to put that before the return statement; I shall leave you to work out for yourself how to do that. Once you have the utility class working, you can use it for other projects, too.