我正在为我的即兴表演剧院制作一个节目,它将帮助我们挑选我们在晚上表演的游戏,没有任何其他游戏的重叠风格。不过,我遇到了一个问题。在下面的代码中,scanner读取一个包含即兴游戏名称的.txt文件,Scanner是一个普通的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;发布于 2019-04-06 01:28:14
我的意思是。您现在大概是在使用getWarmUp,如下所示:
String gamesFileName = "theGamesFile.txt");
Scanner in = new Scanner(System.in);
Scanner games = new Scanner(gamesFileName);
getWarmUp(in, games);但是getWarmUp (或者更确切地说,getWarmUp调用的isWarmUp )可能需要从一开始就重新读取文件。它能够做到这一点的唯一方法是创建一个新的Scanner。为了创建新的Scanner,您需要文件名。所以让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);https://stackoverflow.com/questions/55544852
复制相似问题