在 java 中创建 mad-lib 游戏并接收 NoSuchElementException 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30407259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:03:48  来源:igfitidea点击:

Creating mad-lib game in java and receiving NoSuchElementException method

java

提问by Benjamin Staker

I'm trying to create a java program that recieves a .txt file and plays the game, then prints it all into a new file (named by the user). I've reached the point where all the words have been chosen but am getting a NoSuchElementException message after that. I have a pretty basic knowledge of java and absolutely no clue how to proceed. Anyone have suggestions?

我正在尝试创建一个接收 .txt 文件并玩游戏的 java 程序,然后将其全部打印到一个新文件(由用户命名)中。我已经到了选择所有单词的地步,但在那之后收到了 NoSuchElementException 消息。我对java有非常基本的了解,完全不知道如何进行。有人有建议吗?

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

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

  intro();

  //in order to create the output file first prompts user to decide 
  //whether they want to create a mad-lib, view their mad-lib or quit
  //if 'c' is selected then while loop is exited
  String action = "c";
  String fileName = "fileName";
  while (action.equals("c")) {
     System.out.print("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
     action = console.nextLine();
     action = action.toLowerCase();
     File file = new File(fileName);
     System.out.print("Input file name: ");
     while (!file.exists()) {
        fileName = console.nextLine();
        file = new File(fileName);
        if (!file.exists()) {
           System.out.print("File not found. Try again: ");
        }
     }


     //asks for a file to read from for the mad-lib game
     //and creates file (named by user) to input the information
     System.out.print("Output file name: ");
     String outputName = console.nextLine();
     System.out.println();
     File outputFile = new File(outputName);
     PrintStream output = new PrintStream(outputFile);

     Scanner tokens = new Scanner(file);
     while (tokens.hasNext()) {
        String token = tokens.next();

        //calls the returned placeHolder
        String placeHolder = placeHolder(console, tokens, token);
        String newWord = madLib(console, token, placeHolder);


        //copies each token and pastes into new output file


     }
  }

  while (action.equals("v")) {       
     System.out.print("Input file name: ");
     fileName = console.nextLine();
     File outputFile = new File(fileName);
     if (!outputFile.exists()) { 
        System.out.print("File not found. Try again: ");
        fileName = console.nextLine();
     } else {
        PrintStream output = new PrintStream(outputFile);
        output = System.out;
     }
  }

  while (action.equals("q")) {
  } 

}

public static String madLib(Scanner console, String token, String        
placeHolder) throws FileNotFoundException{
  String word = placeHolder.replace("<", "").replace(">", ": ").replace("-",  
" ");
  String startsWith = String.valueOf(word.charAt(0));
  if (startsWith.equalsIgnoreCase("a") || startsWith.equalsIgnoreCase("e") 
 || 
      startsWith.equalsIgnoreCase("i") || startsWith.equalsIgnoreCase("o") 
 ||
      startsWith.equalsIgnoreCase("u")) {
     String article = "an ";
     System.out.print("Please type " + article + word);
     String newWord = console.next();
     return newWord;
  } else {
     String article = "a ";
     System.out.print("Please type " + article + word);
     String newWord = console.next();
     return newWord;
  }
}

public static String placeHolder(Scanner console, Scanner tokens, String  
 token) throws FileNotFoundException {
   while(!(token.startsWith("<") && token.endsWith(">"))) { 
      //not a placeholder! 
      //continue reading file
      token = tokens.next();
   }
   //outside of this while loop = found a placeholder!!
   String placeHolder = token;
   //returns placeholder to main 
   return placeHolder;
}



//method prints out the introduction to the game
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.");
   System.out.println();
 }
}

Also am currently using a file called simple.txt with the text:

目前我也在使用一个名为 simple.txt 的文件,其中包含以下文本:

I wannabe a <job> when I grow up.
Just like my dad.
Life is <adjective> like that!

This is the full error message:

这是完整的错误消息:

Exception in thread "main" java.util.NoSuchElementException
        at java.util.Scanner.throwFor(Scanner.java:862)
        at java.util.Scanner.next(Scanner.java:1371)
        at MadLibs.placeHolder(MadLibs.java:96)
        at MadLibs.main(MadLibs.java:46)

回答by Matthias

I ran your code and got a NoSuchElementExceptioninstead of a NoSuchFileException. To circumvent this exception you need to check if there are any more tokens while in the method placeHolder. Otherwise, after entering every placeholder you would still search for the next placeholder token although there is no next().

我运行了你的代码并得到了一个NoSuchElementException而不是NoSuchFileException. 要避免此异常,您需要检查方法中是否还有更多标记placeHolder。否则,在输入每个占位符后,您仍会搜索下一个占位符标记,尽管没有next().

Change your code to:

将您的代码更改为:

while(tokens.hasNext() && !(token.startsWith("<") && token.endsWith(">"))) { 
     //not a placeholder! 
     //continue reading file
     System.out.println(token);
     token = tokens.next();
}