简体   繁体   English

为什么会收到NoSuchElementException?

[英]Why am I getting a NoSuchElementException?

This method is essentially a method that reads through a given input file and recursively populates a binary tree with the given information. 此方法本质上是一种读取给定输入文件并用给定信息递归填充二叉树的方法。

The input file is of a very particular format. 输入文件的格式非常特殊。 One line that contains either Q: or A: to indicate whether or not the following line is a question or an answer. 包含Q:或A:的一行以指示下一行是问题还是答案。 It is assumed that all files used with this method will follow this format. 假定与此方法一起使用的所有文件都将遵循这种格式。

Since every file follows the same format, and there should never be an odd number lines, the data shouldn't be fully consumed before reaching one of the nextLine() calls. 由于每个文件都遵循相同的格式,并且永远不应有奇数行,因此在到达nextLine()调用之一之前,不应完全消耗数据。 Nonetheless, the program consistently throws a NoSuchElementException . 尽管如此,该程序始终抛出NoSuchElementException

Is there something I'm missing? 有什么我想念的吗?

private QuestionNode readHelper(Scanner input){
    // Base case: If the given input has no more lines to read.
    if (input.hasNextLine()) {
        String category = input.nextLine();
        String text = input.nextLine();
        QuestionNode root  = new QuestionNode(text);
        if (category.startsWith("Q")) {
            // Recursive case: If there are still questions available to ask
            // more input is read, which replaces the currently stored data.
            root.left = readHelper(input);
            root.right = readHelper(input);
        } else {
            return root;
        }
    }
    return null;
}

The second call to nextLine() within the if statement. if语句中对nextLine()的第二次调用。 There is no guaranty there is a nextLine() after String category = input.nextLine(). 没有保证,在String category = input.nextLine()之后有nextLine()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM