Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Instead of <code>scan.nextInt()</code>, I would use <code>scan.nextLine()</code> again, and then parse the input. If you get a <code>NumberFormatException</code>, you can bark at the user that the input was invlaid.</p> <p>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 <code>nextInt()</code>, the scanner grabs all of the next token and tries to convert it into an <code>Integer</code>. Anything after the Integer token remains to be scanned.</p> <p>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 <code>userName</code> assignment will grab from the end of the number to the next newline. </p> <pre><code> 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); </code></pre> <p>with the input:</p> <pre><code> Enter port number: 123 abc Enter your username: </code></pre> <p>will output </p> <pre><code> serverPort: 123 userName: abc </code></pre> <p>This is because the space is acting as a token separator, and after the <code>scan.nextInt()</code> is called, the space and the <code>abc</code> are still left in the buffer. When the subsequent <code>scan.nextLine()</code> is called, the space and the <code>abc</code> are scanned from the buffer.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload