【问题标题】:Error: java.util.NoSuchElementException - Scanner not behaving as desired错误:java.util.NoSuchElementException - 扫描仪未按预期运行
【发布时间】:2013-06-11 05:17:25
【问题描述】:

扫描仪返回 NoSuch 元素异常错误。你能解释一下为什么会这样吗?

Scanner 现在通过并运行良好,但它没有从第二个 Scanner 调用中获取 nextLine 输入。这可能是一个小调整,但有人可以指出错误是什么。

public class JavaHW1_1 {

private static Scanner userInput = new Scanner(System.in);


public static void main(String[] args) throws IOException {

    String pattern ;
    String fileName = null;



    //      Method to manage user inputs 
    fileName = userInputFileName(userInput);
    pattern = userInputPattern(userInput);

    //      To find the pattern in the file
    //      findPattern();

}


private static String userInputPattern(Scanner userInput) {
    String pattern = "JollyGood";
    System.out.println(". Please enter a pattern to find in the file");

    while(userInput.hasNextLine()){
        pattern = userInput.nextLine();
        System.out.println("The pattern to be searched: "+ pattern);
    }
    userInput.close();

    return pattern;
}


private static String userInputFileName(Scanner userInput) throws IOException {
    String path = "./src";
    String files, fileName;
    File folder = new File(path);
    File[] listOfFiles = folder.listFiles();

    System.out.println("Please input the desired file name:\n");
    System.out.println("Some suggestions:\n");
     for (int i = 0; i < listOfFiles.length; i++) 
      {

       if (listOfFiles[i].isFile() && listOfFiles[i].getName().toLowerCase().endsWith(".txt")) 
       {

       files = listOfFiles[i].getName();
       System.out.println(files);
          }
      }

     int userAttempt = 0;

     do{
     fileName = userInput.nextLine();

     if(fileName.toLowerCase().endsWith(".txt")){
         System.out.println("The file name entered is in correct format");
         File file = new File("./src",fileName);

         try {
            file.createNewFile();
            System.out.println("File is created. Please enter text to be written in the file. End the content with \"eof\"");
            InputOutput(file.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }

         userAttempt = 10;
     }
     else
         {System.out.println("Please enter correct format file with .txt extension");
         userAttempt++;}
     }while (userAttempt <10);

    return fileName;
}




private static void InputOutput(String fName) throws IOException {

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    BufferedWriter out = null;
    try {
        out = new BufferedWriter(new FileWriter("./src/" + fName));
        String inputLine = null;
        do {
            inputLine=in.readLine();
            out.write(inputLine);
            out.newLine();
        } while (!inputLine.equalsIgnoreCase("aaa"));
        System.out.print("Write Successful");
    } catch(IOException e1) {
        System.out.println("Error during reading/writing");
    } finally {
        out.close();
        in.close();
    }

}


private static void findPattern() {
    // TODO Auto-generated method stub

}


}

【问题讨论】:

标签: java algorithm loops if-statement java.util.scanner


【解决方案1】:

基于this SO,您可能正在关闭Scanner 并创建一个新的以从System.in 读取,这通过查看您的代码是有意义的。

所以我对你的代码建议是通过参数接收扫描器,如下所示:

public static void main(String[] args){

    Scanner scan = new Scanner (System.in);
    String pattern = userInputPattern(scan);
    String test = readSomethingElse(scan);
}

private static String readSomethingElse(Scanner scan) {
   System.out.println(". Read something else");
    return scan.nextLine();
}

private static String userInputPattern(Scanner scan) {

    String pattern = "JollyGood";
    System.out.println(". Please enter a pattern to find in the file");
    pattern = scan.nextLine();
    System.out.println("The pattern to be searched: "+ pattern);
    return pattern;
}

【讨论】:

  • 啊,好一个。我同意,也许 Scanner 由缓冲区支持,如果您尝试使用多个 Scanner 进行扫描,则输入可能已经被前一个扫描仪的缓冲区“吃掉”
  • 如果问题公开Scanners,是不是最好做一个try { ... } finally { [close Scanner] }或者使用Java 7的自动资源管理?
  • @jpmc26 我没有玩过 Java 7,所以不知道这将如何工作......关于尝试/最后这是一个有趣的解决方案,我将对其进行编辑并添加到答案中作为第二种选择。
  • 这有助于我没有收到任何错误,但它没有第二次要求输入。我的扫描输入在一种方法中定义并不简单,一种方法中有多个输入。
  • @jpmc26 关于 try/finally 解决方案,它不起作用,因为在关闭扫描仪时 System.in 已关闭。
【解决方案2】:

如果您将 EOF 直接传递到标准输入,则可能会发生这种情况。例如(在 Windows 中):

java com.myprog.MainClass
^Z
Exception in thread "main" java.util.NoSuchElementException: No line found
  at java.util.Scanner.nextLine(Unknown Source)
  ....

上面的 ^Z 代表 Windows 命令提示符下的 Ctrl-Z,它是一个 EOF 信号

如果向用户提供没有任何先前数据的 EOF,您需要考虑您的要求和处理/显示错误

【讨论】:

  • 看来你可能是对的,但我应该如何纠正它。因为如果我用任何其他字符串“eof”或“;”结束先前扫描仪中的内容或 "aaa" 它仍然会抛出相同的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 2017-05-15
相关资源
最近更新 更多