I want to repeatedly request an IP address and a port (string followed by number) until valid input is entered.
Here is the code:
This works fine if a string is entered followed by an integer.
But if I enter a string followed by another string I get:
Enter IP address to connect to: 192.168.0.2
you entered ip: 192.168.0.2
Enter port number to connect to: seven
You must enter IP address as a string and port as a number
Enter IP address to connect to: you entered ip:
Enter port number to connect to: 22
You entered IP: and Port: 22
How can I recover properly. It is fine if user is prompted again for the string part. I thought reset would fix things in the scanner?
input.nextInt(); attempts to read only integer value, so when exception is thrown you enter catch block without picking the \n character you entered before as part of your input. Add input.nextLine(); at the beginning of your catch block and it should do the trick.
The quieter you are, the more you are able to hear.
Joined: Jul 16, 2011
Kemal Sokolovic wrote:input.nextInt(); attempts to read only integer value, so when exception is thrown you enter catch block without picking the \n character you entered before as part of your input. Add input.nextLine(); at the beginning of your catch block and it should do the trick.
Note that if you really want to check if user has provided valid input, you should validate IP address too. It has specific format, so it won't be difficult to check. In this case, user can enter "ip address" for ip address - it's also a string, so you're just moving on like valid one is entered.
Also you can validate port number to be in the specified valid range.
Don’t even try to recover from an IME. Rob Spoor pointed out a few years back that an IME is always avoidable. There are two pitfalls about using Scanner for keyboard input.
1: You can get blank lines read in, as KS has already mentioned.
2: You think you have to catch IMEs, but you don’t.
Some books tell you that nextLine gets the next line, but it doesn’t. There is a different explanation about the blank line problem here.
When I was learning, we all created utility classes for keyboard input, which used BufferedReaders. I still think a utility class for keyboard input is a good idea. There is an example of what I mean here. You can overload that method to take maximum and minimum parameters, so you can enhance the loop to print something like “Value must lie between 1 and 999: please try again:- ” and validate the input before you return it.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: Problem recovering from InputMismatchException in Scanner class