[英]How to use the Scanner in a separate method without calling it multiple times
[英]Is It Possible to Use a File Scanner Multiple Times Without Declaring Multiple Scanners?
我正在為我的即興劇院制作一個程序,該程序將幫助我們挑選晚上在演出中玩的游戲,而不會與任何其他游戲的風格重疊。 不過我遇到了問題。 在下面的代碼中,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
調用)可能需要從頭開始重新讀取文件。 它可以做到這一點的唯一方法是創建一個新的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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.