代码之家  ›  专栏  ›  技术社区  ›  titianvalero

线程“main”java中出现异常。util。NoSuchElementException:未找到行3[重复]

  •  -1
  • titianvalero  · 技术社区  · 7 年前

    在此代码中,引发以下异常:

    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进行扩展的客户端类中,并从run()方法调用。

    1 回复  |  直到 7 年前
        1
  •  0
  •   DodgyCodeException    7 年前

    不要关闭扫描仪 teclado 在里面 setConnection() . 关闭扫描仪也会关闭其关联的流。然后在 askToDo ,当您创建另一个扫描仪时,系统。中已关闭。

    您应该有一个用系统初始化的顶级静态扫描对象。在中,并在类中的任何位置使用该方法,而不是在每个方法中创建新的扫描程序。