这可能是一个非常简单的问题,但我一生都无法弄清楚出了什么问题。我刚开始用这个自学Java:http: //math.hws.edu/javanotes/
作为参考,该程序依赖于该教科书中名为“TextIO”的输入/输出类。你可以在这里找到它的代码:http: //math.hws.edu/javanotes/source/TextIO.java。
我做了一个超级简单的二十一点程序,我决定尝试记录高分:赢得的游戏数和总金额。该程序应该从文本文件中读取分数,然后在用户获得更高分数时重新写入该文本文件中的信息。
无论如何,一切似乎都很好,除了我希望你能够输入你的名字来赢得最多的比赛或最多的钱。我对其进行了超级简化,因此它只询问您的姓名两次以尝试查看问题所在(而不是仅询问您是否真的获得了高分),问题是它会打印“输入您的姓名”两个问题次,但只读取一次输入,奇怪的是它只读取第一个输入!这是代码:
/* This program allows the user to play a game of
enter code here`* blackjack against the computer. The user can bet money
* the game will keep track of total winnings as well as
* the number of games won.
*/
public class BlackjackGame {
//keep track of highest scoring players so far
static String nameForGames; //name of person who won most games
static String nameForWinnings; //name of person who won most money
static int maxGames; //highest # of games won
static int maxWinnings; //highest amount of money earned
static int gamesWon = 0; //keeps track of total games won by user
static int money = 100; //total pot of money available for betting
private static Deck deck = new Deck();
static boolean wantToPlay; //answers whether the user wants to keep playing
public static void main(String[] args) {
//load the high score data from the scores.txt file
TextIO.readFile("scores.txt");
nameForGames = TextIO.getlnString();
maxGames = TextIO.getlnInt();
nameForWinnings = TextIO.getlnString();
maxWinnings = TextIO.getlnInt();
TextIO.putln(nameForGames + " " + maxGames + " " + nameForWinnings + " " + maxWinnings);
TextIO.readStandardInput();
introduction();
TextIO.put("Would you like to play");
wantToPlay = TextIO.getBoolean();
//user can keep playing indefinitely until they decide to stop
while (wantToPlay == true) {
playGame();
if (wantToPlay == false) {
break;
}
TextIO.put("Play again?");
wantToPlay = TextIO.getBoolean();
}
//print results of gameplay
TextIO.putln("\nThanks for playing!");
TextIO.putln("You won " + gamesWon + " games and walk away with $" + money + ".");
TextIO.putln();
//THIS IS THE PART THAT DOESNT MAKE SENSE? WHY IS IT ONLY READING INPUT ONCE?
TextIO.put("Enter your name: ");
nameForWinnings = TextIO.getln();
TextIO.putln();
TextIO.put("Enter your name: ");
nameForGames = TextIO.getln();
//Save new high scores to scores.txt.
TextIO.writeFile("scores.txt");
TextIO.putln(nameForGames);
TextIO.putln(maxGames);
TextIO.putln(nameForWinnings);
TextIO.putln(maxWinnings);
//Re-read the data from the file, and display to the player.
System.out.println("The high scores are:");
TextIO.readFile("scores.txt");
nameForGames = TextIO.getlnString();
maxGames = TextIO.getlnInt();
nameForWinnings = TextIO.getlnString();
maxWinnings = TextIO.getlnInt();
TextIO.writeStandardOutput();
TextIO.putln(nameForGames + " won " + maxGames + " games!");
TextIO.putln(nameForWinnings + " won $" + maxWinnings + " total cash!");
} //end main()