读取文本文件的最后一行后出现 NoSuchElementException 错误

NoSuchElementException error after reading the final line of a text file

我尝试读取的文本文件示例

One of the most <adjective> characters in fiction is named
"Tarzan of the <plural-noun> ." Tarzan was raised by a/an
<noun> and lives in the <adjective> jungle in the
heart of darkest <place> . He spends most of his time
eating <plural-noun> and swinging from tree to <noun> .
Whenever he gets angry, he beats on his chest and says,
" <funny-noise> !" This is his war cry. Tarzan always dresses in
<adjective> shorts made from the skin of a/an <noun>
and his best friend is a/an <adjective> chimpanzee named
Cheetah. He is supposed to be able to speak to elephants and
<plural-noun> . In the movies, Tarzan is played by <person's-name> .

我当前程序的代码

import java.util.*;
import java.io.*;

public class MadLibs {
   public static void main(String[] args) throws FileNotFoundException {
      intro();
      System.out.println();
      Scanner console = new Scanner(System.in);

      boolean continueGame = true;

      while (continueGame == true) {
         continueGame = gameMenu(console);
      } 
   }

   public static void intro() {
      System.out.println("Welcome to the game of Mad Libs.");
      System.out.println("I will ask you to provide various words");
      System.out.println("and phrases to fill in a story.");
      System.out.println("The result will be written to an output file.");
   }

   public static boolean gameMenu(Scanner console) throws FileNotFoundException {
      System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
      String userChoice = console.nextLine();

      if (userChoice.equalsIgnoreCase("c")) {
         createMadLib(console);
         return true;
      } else if (userChoice.equalsIgnoreCase("v")) {
         viewMadLib(console);
         return true;
      } else if (userChoice.equalsIgnoreCase("q")) {
         return false;
      } else {
         return true; //keep continuing even if user input is irrelevant 
      }
   }

   public static void createMadLib(Scanner console) throws FileNotFoundException {
      System.out.print("Input file name: ");
      String fileName = console.nextLine();
      File textFile = new File(fileName);

      while (!textFile.exists()) {
         System.out.print("File not found. Try again: ");
         fileName = console.nextLine();
         textFile = new File(fileName);
      }
      System.out.print("Output file name: ");
      String output = console.nextLine();
      PrintStream outputFile = new PrintStream(output);

      Scanner fileRead = new Scanner(textFile);

      while (fileRead.hasNextLine()) {
         String word = fileRead.next();

         if (word.startsWith("<") && word.endsWith(">")) {
            char vowel = word.charAt(1);

            String beforeVowel = "";
            if (vowel == 'a' || vowel == 'A' ||
                vowel == 'e' || vowel == 'E' ||
                vowel == 'i' || vowel == 'I' ||
                vowel == 'o' || vowel == 'O' ||
                vowel == 'u' || vowel == 'U') {
               beforeVowel = " an";
            } else {
               beforeVowel = " a";
            }
            word = word.replace("<", " ");
            word = word.replace(">", " ");
            word = word.replace("-", " ");
            System.out.print("Please type" + beforeVowel + word + ": ");
            String inputWord = console.nextLine();
            outputFile.print(" " + inputWord + " ");
         } else {
            outputFile.print(" " + word + " ");
         }
      }
      System.out.println("Your mad-lib has been created!");
   }

相关错误的完整堆栈跟踪

Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at MadLibs.createMadLib(MadLibs.java:58)
    at MadLibs.gameMenu(MadLibs.java:29)
    at MadLibs.main(MadLibs.java:13)

它发生在程序读取文本文件的最后一行之后。我认为错误的主要原因可能是它仍在继续搜索最后一行之后的下一个占位符。

您可以尝试创建新的 Scanner,如下所示。

while (fileRead.hasNextLine()) {
    Scanner lineRead = new Scanner(fileRead.nextLine());
    while (lineRead.hasNext()) {
         String word = fileRead.next();
..
..
..

如@snr 所述,读取输入文件似乎存在问题。由于没有新行,您的扫描仪失败了。您需要使用 lineRead.hasNext() 而不是 lineRead.hasNextLine()

您的代码将是:

import java.util.*;
import java.io.*;

public class MadLibs {
    public static void main(String[] args) throws FileNotFoundException {
        intro();
        System.out.println();
        Scanner console = new Scanner(System.in);

        boolean continueGame = true;

        while (continueGame == true) {
            continueGame = gameMenu(console);
        }
    }

    public static void intro() {
        System.out.println("Welcome to the game of Mad Libs.");
        System.out.println("I will ask you to provide various words");
        System.out.println("and phrases to fill in a story.");
        System.out.println("The result will be written to an output file.");
    }

    public static boolean gameMenu(Scanner console) throws FileNotFoundException {
        System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
        String userChoice = console.nextLine();

        if (userChoice.equalsIgnoreCase("c")) {
            createMadLib(console);
            return true;
        } else if (userChoice.equalsIgnoreCase("v")) {
            return true;
        } else if (userChoice.equalsIgnoreCase("q")) {
            return false;
        } else {
            return true; //keep continuing even if user input is irrelevant
        }
    }

    public static void createMadLib(Scanner console) throws FileNotFoundException {
        System.out.print("Input file name: ");
        String fileName = console.nextLine();
        File textFile = new File(fileName);

        while (!textFile.exists()) {
            System.out.print("File not found. Try again: ");
            fileName = console.nextLine();
            textFile = new File(fileName);
        }
        System.out.print("Output file name: ");
        String output = console.nextLine();
        PrintStream outputFile = new PrintStream(output);

        Scanner fileRead = new Scanner(textFile);

        while (fileRead.hasNext()) {
            String word = fileRead.next();

            if (word.startsWith("<") && word.endsWith(">")) {
                char vowel = word.charAt(1);

                String beforeVowel = "";
                if (vowel == 'a' || vowel == 'A' || vowel == 'e' || vowel == 'E' || vowel == 'i' || vowel == 'I' || vowel == 'o' || vowel == 'O' || vowel == 'u' || vowel == 'U') {
                    beforeVowel = " an";
                } else {
                    beforeVowel = " a";
                }
                word = word.replace("<", " ");
                word = word.replace(">", " ");
                word = word.replace("-", " ");
                System.out.print("Please type" + beforeVowel + word + ": ");
                String inputWord = console.nextLine();
                outputFile.print(" " + inputWord + " ");
            } else {
                outputFile.print(" " + word + " ");
            }
        }

        System.out.println("Your mad-lib has been created!");

    }
}

由于没有 viewMadLib 函数,我将其从答案中删除。

希望对您有所帮助