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

标签 java file nosuchelementexception

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

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();
..
..
..

关于java - 读取文本文件的最后一行后出现 NoSuchElementException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58851712/

相关文章:

c - 使用 C 中的结构将数据存储到动态数组中

c - 如何在C程序结束时自动打开.txt文件?

java - 没有这样的元素异常扫描器

java - 读取文件时出现 NoSuchElementException

java - 如何通过本地主机从 JavaMail 发送邮件

java - 从字符串中读取 rdf 模型

java - 如何在 Jetty 上的 Spring 应用程序中将 jsessionid cookie 路径更改为服务器根目录?

php - fatal error : Call to a member function prepare() on a non-object

java - 断言网页中缺少元素,给出 NoSuchElementException

java - Android Wear 无法唤醒屏幕