这可能是一个非常简单的问题,但我不能为我的生活弄清楚出了什么问题。我刚开始用Java自学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()
答案 0 :(得分:1)
在读取用户名之前调用的getBoolean
方法似乎不会从流中删除行分隔符。这意味着第一次调用readln
将返回该行剩下的内容,即使它是一个空字符串。查看可用的方法,您可能应该使用getlnBoolean
。