线程 "main" java.util.NoSuchElementException 中的异常:找不到行 3
Exception in thread "main" java.util.NoSuchElementException: No line found 3
在这段代码中,抛出这个异常:
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)
抛出错误的方法:
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;
}
但是在其他代码之前执行的这段代码中,没有抛出任何错误。
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:此方法位于 Thread 扩展的客户端 class 中,并从 运行() 方法中调用。
不要在 setConnection()
中关闭扫描程序 teclado
。关闭 Scanner 也会关闭其关联的流。然后在askToDo
中,当你创建另一个Scanner时,System.in已经关闭了。
您应该有一个顶级静态 Scanner 对象,用 System.in 初始化,并在 class 中的任何地方使用它,而不是在每个方法中创建一个新的 Scanner。
在这段代码中,抛出这个异常:
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)
抛出错误的方法:
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;
}
但是在其他代码之前执行的这段代码中,没有抛出任何错误。
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:此方法位于 Thread 扩展的客户端 class 中,并从 运行() 方法中调用。
不要在 setConnection()
中关闭扫描程序 teclado
。关闭 Scanner 也会关闭其关联的流。然后在askToDo
中,当你创建另一个Scanner时,System.in已经关闭了。
您应该有一个顶级静态 Scanner 对象,用 System.in 初始化,并在 class 中的任何地方使用它,而不是在每个方法中创建一个新的 Scanner。