【问题标题】:NoSuchElementException error after reading the final line of a text file读取文本文件的最后一行后出现 NoSuchElementException 错误
【发布时间】:2023-04-07 01:48:01
【问题描述】:

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

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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢! hasNextLine 给我带来了很多问题。
    【解决方案2】:

    正如@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 函数,我将其从答案中删除。

    希望对你有帮助

    【讨论】:

    • 快速提问,如果我想在程序打印每一行后添加换行符,是否还需要使用 lineRead.hasNextLine()?
    • 我认为您可以使用更实用的方式来执行此操作,并创建测试,以便您可以看到行为。或者调试也是一种解决方案...你必须给@snr答案,他找到了解决方案。
    猜你喜欢
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    相关资源
    最近更新 更多