可能导致NoSuchElementException吗?

问题描述 投票:0回答:2

我花了大约两个小时来寻找解决方案,但一无所获。据我所知,.nextLine()应该等待输入,通常会这样。但是在这段代码中,它抛出java.util.NoSuchElementException: No line found。谁能解释可能导致此问题的原因?

请注意,我是Java新手。

这是令人不安的一段代码

private void interactiveMode() throws IOException {
        System.out.println("Launching remote collection manager");
        try (Scanner userCommandReader = new Scanner(System.in)){                                                      
            System.out.println("Collection is ready for formatting");
            System.out.println("Waiting for input. Type help for list of commands");
            Thread.sleep(1000);                    

            String testString = userCommandReader.nextLine();
            System.out.println(testString);
        }catch (Exception e ) {e.printStackTrace();}
}

这里有完整的例外,以防万一:

java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at client.ConnectToServer.interactiveMode(ConnectToServer.java:81) //line 81:String  testString = userCommandReader.nextLine();
    at client.ConnectToServer.server_tunnel(ConnectToServer.java:44)
    at client.Main.main(Main.java:19)
java exception java.util.scanner nosuchelementexception
2个回答
0
投票

不知道为什么,但是您的应用程序无法从标准输入中读取,或者这样做很慢。

尝试等待新行,看看有什么区别。

    System.out.println("Launching remote collection manager");
    try (Scanner userCommandReader = new Scanner(System.in)) {
        System.out.println("Collection is ready for formatting");
        System.out.println("Waiting for input. Type help for list of commands");
        while(userCommandReader.hasNextLine()) {
            String testString = userCommandReader.nextLine();
            System.out.println(testString);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

我删除了不需要的Thread.sleep


0
投票

问题的原因是,由于Scanner语法,try-with-resources正在关闭。请注意,一旦userCommandReader关闭,System.in也将关闭,无法再次打开。如下进行:

private void interactiveMode() throws IOException {
    System.out.println("Launching remote collection manager");
    Scanner userCommandReader = new Scanner(System.in)                                                    
    System.out.println("Collection is ready for formatting");
    System.out.println("Waiting for input. Type help for list of commands");
    Thread.sleep(1000);                    

    String testString = userCommandReader.nextLine();
    System.out.println(testString);    
}
© www.soinside.com 2019 - 2024. All rights reserved.