簡體   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