Use of hasNextLine in Java, won't read NextLine after NextInt
Question
I am trying to get this to work
System.out.println("Please enter what SOCKET NUMBER you" +
"wish to connect to");
int sockname = Integer.parseInt(inFromUser.nextLine());
System.out.println("Please enter what HOSTNAME you" +
"wish to connect to");
String hostname = inFromUser.nextLine();
The problem is that I can't get hostname to equal whatever the user input. I thought it had to do with hasNext or a variant of that, but I'm not sure. Any thoughts?
Solution
There might be "\n" in the input buffer after nextLine(), so next call just reads it and returns. You need to clear the buffer after reading int
inFromUser.skip("\\n+");
OTHER TIPS
java.io.BufferedReader has a readLine() method. Use that. If you're using Scanner.nextLine(), then you should know that if your position is just before a newline, you'll get an empty string. However, the next nextLine would indeed return a full line of text (the same as readLine would).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow