0

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?

asafc
  • 349
  • 3
  • 16
  • @Arc676 You should find one that is the same problem and vote to close. – user1803551 Oct 21 '15 at 13:53
  • 1
    @Arc676 i rather think it´s because he closes the `PrintStream` associated with `System.in` and not the common `nextLine` after `nextFoo` answer. – SomeJavaGuy Oct 21 '15 at 13:53
  • The best match I've found: http://stackoverflow.com/questions/23621668/java-closing-scanner-and-resource-leak – Jiri Tousek Oct 21 '15 at 13:57
  • Or this one: http://stackoverflow.com/questions/4565854/why-is-scanner-skipping-inputs-from-the-user – Arc676 Oct 21 '15 at 13:58
  • 1
    @KevinEsche A _PrintStream_ associated with _System.in_? And I thought System.in is of type InputStream ... – Tom Oct 21 '15 at 14:31

1 Answers1

0

Don't close() the Scanner. When you close the scanner, it closes System.in, so your second scanner has nothing to read.

When using a Scanner on System.in, you should only ever create one, and reuse it.

Andreas
  • 138,167
  • 8
  • 112
  • 195