I'm writing a small PvP game in Java that has a server (host) and a client (second player), that communicate over a pair of sockets.
In case a player wishes to join a pre-established game, I prompt for the IP address of the game's host over the standard input (System.in
). In order to do that I use a Scanner
instance. When I try to read the next line and feed it into a String
constructor, I receive the following exception:
Exception in thread "Thread-0" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at BattleshipServer.run(BattleshipServer.java:45)
at java.lang.Thread.run(Thread.java:745)
this is in spite of the fact that the 'enter' key on the keyboard hasn't been pressed yet.
There is only one previous use of the standard input:
public static void main(String[] args){
if (args.length != 1)
printErrorMessageAndExit(USAGE_ERROR_MESSAGE);
int port = Integer.parseInt(args[0]);
if (port < 0 || port > 65535)
printErrorMessageAndExit("Error: invalid port number");
System.out.println("Do you wish to join or host a game? ");
Scanner scanner = new Scanner(System.in);
String selection = scanner.nextLine();
scanner.close();
if (!selection.equals("join") && !selection.equals("host"))
printErrorMessageAndExit("Error: please select 'join' or 'host'");
.
.
.
}
and the second use which causes the error: (error occurs on the third line)
System.out.println("Please enter host's IP address: ");
Scanner scanner = new Scanner(System.in);
String address = scanner.nextLine();
scanner.close();
I can't seem to find the problem, but I do know that the first read from the standard input clears the buffer, so it is empty in the second call, but it should block until the 'enter' key is pressed again!
Could this be because the first scanner instance is in a static
method, while the second instance is in an instance of the same class?