Mana
Mana

Reputation: 49

NoSuchElementException error after reading the final line of a text file

Example of text file that I am trying to read in

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> .

My current program's code

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!");
   }

the full stack trace of the error in question

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)

It occurs right after the final line of the text file is read by the program. I believe the main cause of the error may be due to the fact that it is still continuing to search for the next placeholder after the last line.

Upvotes: 3

Views: 223

Answers (2)

Driss NEJJAR
Driss NEJJAR

Reputation: 978

As @snr mentionned, It seems that there is an issue with reading the input file. Since there is no new line, your scanner fail. You need to use lineRead.hasNext() instead of lineRead.hasNextLine()

Your code would be:

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!");

    }
}

Since, there is no viewMadLib function, I removed it from my answer.

Hope this helps

Upvotes: 0

You can try to create new Scanner as following.

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

Upvotes: 2

Related Questions