我正在为我的即兴剧院制作一个程序,它将帮助我们挑选出我们在晚上的演出中玩的游戏,而不会与任何其他游戏的风格重叠。但我遇到了问题。在下面的代码中,Scanner scWU 读取包含即兴游戏名称的 .txt 文件,Scanner sc 是普通的 System.in 扫描器。
我在下面粘贴了两个方法。 getWarmUp() 在被视为某个类别(在本例中为热身游戏类别)的可行游戏后返回字符串(游戏)。 isWarmUp()读取warmupgames.txt文件,查看进入的游戏是否确实是热身游戏
我的问题是:如果用户无法输入游戏名称(并且 isWarmUp 返回 false),我如何重新启动该方法或重置文件顶部的 scWU 扫描仪?我需要申报多台扫描仪吗?或者,在用户第一次无法正确进入游戏后,我可以轻松地让同一个扫描仪再次扫描文件吗? (注意:我知道第 25 行的 while 循环是一个无限循环。这就是我希望解决这个问题的地方)
我会回答有关我的代码的任何困惑
public static String getWarmUp(Scanner sc, Scanner scWU)
{
String prompt = "What warm-up game will you choose? \n" +
"(NOTE: Type game as it's written on the board. Caps and symbols don't matter.)\n" +
"> ";
System.out.print(prompt);
String game = sc.nextLine();
//This while loop is infinite. This is where I'm hoping to somehow allow the scanner to reset and
//read again on a failed input
while(!warmUp)
{
warmUp = isWarmUp(scWU, game);
if(!warmUp)
System.out.println("That's not a warm-up game, try again.");
}
return game;
}
public static boolean isWarmUp(Scanner scWU1, String game)
{
int lineNum = 0;
while(scWU1.hasNextLine())
{
String line = scWU1.nextLine();
lineNum++;
if(line.equalsIgnoreCase(game))
return true;
}
return false;
最佳答案
这就是我的意思。想必您现在正在使用 getWarmUp
,如下所示:
String gamesFileName = "theGamesFile.txt");
Scanner in = new Scanner(System.in);
Scanner games = new Scanner(gamesFileName);
getWarmUp(in, games);
但是 getWarmUp
(或者更确切地说,isWarmUp
,getWarmUp
调用)可能需要从头开始重新读取文件。实现此目的的唯一方法是创建一个新的扫描仪
。您需要文件名才能创建新的扫描仪
。因此,让 getWarmUp
将文件名作为参数,而不是打开的 Scanner
:
public static String getWarmUp(Scanner sc, String gamesFn)
{
boolean warmUp = false;
while(!warmUp)
{
String prompt = "What warm-up game will you choose? \n" +
"(NOTE: Type game as it's written on the board. Caps and symbols don't matter.)\n" +
"> ";
System.out.print(prompt);
String game = sc.nextLine();
Scanner scWU = new Scanner(gamesFn);
warmUp = isWarmUp(scWU, game);
scWU.close();
if(!warmUp)
System.out.println("That's not a warm-up game, try again.");
}
return game;
}
然后这样调用它:
String gamesFileName = "theGamesFile.txt");
Scanner in = new Scanner(System.in);
getWarmUp(in, gamesFileName);
关于java - 是否可以多次使用文件扫描程序而不声明多个扫描程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55544852/