繁体   English   中英

为什么会收到NoSuchElementException?

[英]Why am I getting a NoSuchElementException?

此方法本质上是一种读取给定输入文件并用给定信息递归填充二叉树的方法。

输入文件的格式非常特殊。 包含Q:或A:的一行以指示下一行是问题还是答案。 假定与此方法一起使用的所有文件都将遵循这种格式。

由于每个文件都遵循相同的格式,并且永远不应有奇数行,因此在到达nextLine()调用之一之前,不应完全消耗数据。 尽管如此,该程序始终抛出NoSuchElementException

有什么我想念的吗?

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;
}

if语句中对nextLine()的第二次调用。 没有保证,在String category = input.nextLine()之后有nextLine()。

暂无
暂无

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

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