When I run the following code it stops to let me enter servername and them port number, after that it is supposed to stop and let me enter username but it never pauses for s
Instead of scan.nextInt()
, I would use scan.nextLine()
again, and then parse the input. If you get a NumberFormatException
, you can bark at the user that the input was invlaid.
The reason why you need to do something like this is that you still have a newline sitting at the end of your serverPort input. When you use nextInt()
, the scanner grabs all of the next token and tries to convert it into an Integer
. Anything after the Integer token remains to be scanned.
To prove this, with your original code, if you put a token separator, like a space, after your server port input and then add some text, you will find that your subsequent userName
assignment will grab from the end of the number to the next newline.
System.out.println("\nEnter port number:");
Integer serverPort = scan.nextInt();
System.out.println("\nEnter your username:");
String userName = scan.nextLine();
System.out.println("\nserverPort: " + serverPort
+ "\nuserName: " + userName);
with the input:
Enter port number:
123 abc
Enter your username:
will output
serverPort: 123
userName: abc
This is because the space is acting as a token separator, and after the scan.nextInt()
is called, the space and the abc
are still left in the buffer. When the subsequent scan.nextLine()
is called, the space and the abc
are scanned from the buffer.