java - 为什么我会收到 NoSuchElementException?

标签 java recursion binary-tree 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()。

关于java - 为什么我会收到 NoSuchElementException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35822585/

相关文章:

java - 无法在 linux 中从 java 调用 mysqldump

javascript - ckeditor拖放txt文件

java - 使用递归方法对数组进行排序

java - 二叉树 - 检查它是否是高度平衡的

java - 二叉树中节点的路径

JAVA - 检查面板中最近的对象

Java 字符串数组归并排序

java - 线程中的异常 "main"java.lang.IndexOutOfBoundsException : Index: 0, 大小 : 0?

java - 识别数组中的连接元素

java - 如何返回二叉树中序遍历的迭代器?