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?
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.
Thanks for that.
This works now.
Also you can validate port number to be in the specified valid range.
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.