线程"main"中的异常java.util.NoSuchElementException:找不到行3 [英] Exception in thread "main" java.util.NoSuchElementException: No line found 3

查看:710
本文介绍了线程"main"中的异常java.util.NoSuchElementException:找不到行3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中,抛出此异常:

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)   

引发错误的方法:

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:此方法在Thread扩展的Client类中,并从run()方法调用.

PD: This methods are in the Client class that is extended of Thread and are called from the run() method.

推荐答案

不要关闭setConnection()中的扫描仪teclado.关闭扫描程序也会关闭其关联的流.然后在askToDo中,当您创建另一个扫描仪时,System.in已经关闭.

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.

您应该有一个用System.in初始化的顶级静态Scanner对象,并在类中的任何地方使用该对象,而不是在每个方法中创建一个新的Scanner.

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.

这篇关于线程"main"中的异常java.util.NoSuchElementException:找不到行3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆