In this code, throws me this exception:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.cristianvalero.filetransfers.main.client.Client.askToDo(Client.java:98)
at com.cristianvalero.filetransfers.main.client.Client.run(Client.java:64)
at com.cristianvalero.filetransfers.main.client.Client.main(Client.java:36)
Method that throws the error:
private String askToDo()
{
Scanner teclado = new Scanner(System.in);
System.out.print("What would you like to do? [help]: ");
String a = teclado.nextLine().toLowerCase();
teclado.close();
return a;
}
But in this code that executes before the other code, no throws any error.
private void setConnection() //Type of bookmarks "servers":["casa:1.1.1.1:3306", "trabajo:1.1.1.1:7809"]
{
Scanner teclado = new Scanner(System.in);
System.out.print("New server [N] or Connect previous server [P]: ");
final String typed = teclado.nextLine().toLowerCase();
if (typed.equals("n"))
noHaveServers(teclado);
else if (typed.equals("p"))
{
if (ServerList.getAllServers(CONFG).size() == 0)
noHaveServers(teclado);
else
haveServers(teclado);
}
else
{
System.out.println("Sorry, I can't understand you.");
teclado.close();
setConnection();
}
teclado.close();
}
PD: This methods are in the Client class that is extended of Thread and are called from the run() method.
Don't close the Scanner teclado
in setConnection()
. Closing a Scanner also closes its associated stream. Then in askToDo
, when you create another Scanner, System.in is already closed.
You should have a single top-level static Scanner object, initialized with System.in, and use that everywhere in your class instead of creating a new Scanner in each method.