Andrew Lalis
Andrew Lalis

Reputation: 974

Getting user input in a while loop

I am trying to create a basic IRC by using Kryonet for communication. The problem I am having is that in my code, I cannot safely have a main while loop that allows the user to type and send a message, because Scanner gives an error and appears to skip past the call to nextLine(). What I want to do is have the Scanner wait for user input before continuing.

    Scanner input = new Scanner(System.in);

    while (running){

        System.out.print(":");

        message.text = input.nextLine();

        client.sendTCP(message);

    }

    input.close();

To be more precise, the program will first put a ":" at the beginning of the line, and then will get whatever the user types after they press enter, and then send that off to the server. Here's the error I'm getting:

:Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at com.andrewlalisofficial.ChatClient.main(ChatClient.java:51)

Upvotes: 0

Views: 89

Answers (2)

Cinnam
Cinnam

Reputation: 1922

You are closing System.in (through Scanner) - don't do that. If you close it and then try to read from it again with a new Scanner, it will throw the exception you posted.

Upvotes: 2

alesegdia
alesegdia

Reputation: 548

Scanner input = new Scanner(System.in);
while (true){
    System.out.print(":");
    String text = input.nextLine();
    System.out.println(text);
}

This is working here.

Upvotes: 0

Related Questions