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

问题描述 投票:0回答:2

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

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)

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

java file nosuchelementexception
2个回答
0
投票

您可以尝试如下创建新的Scanner

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

0
投票

如@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功能,因此我从答案中删除了它。

希望这会有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.