java使用文本文件存储和显示多个用户的信息
我正在编写一个程序,允许用户玩老虎机,然后将他们的名字和分数存储到一个文本文件中。在节目开始和老虎机游戏结束时,有一个包含三个选项的菜单,用户可以从中选择:
- 玩新游戏
- 查看分数
- 退出游戏李>
当用户按2时,程序应显示每场比赛的分数,而不仅仅是刚刚玩过的比赛;因此,每当用户播放时,他们的信息都应该附加到已经存在的文件中,score.txt
我的问题是,每当我试图读取这个文件时,它只会显示刚刚玩过的游戏的分数。以下是游戏结束后运行的代码:
System.out.println("Game over! Your score has been written to scores.txt" + name + "!");
System.out.print("Actions:\n");
System.out.println("1. Start a new game\n" +
"2. View scores\n" +
"3. Exit ");
System.out.println("Please select an action: ");
action = keyboard.nextInt();
while (action == 2) {
File myFile = new File("score.txt");
Scanner inputFile = new Scanner(myFile);
if (myFile.exists()) {
while (inputFile.hasNext()) {
name = inputFile.nextLine();
System.out.println("Name\n------\n" + name + "\n");
total = inputFile.nextDouble();
System.out.printf("Scores\n------\n$%.2f\n", total);
System.out.println();
}
} else
System.out.println("There are no scores to display at this time.");
System.out.print("Actions:\n");
System.out.println("1. Start a new game\n" +
"2. View scorse\n" +
"3. Exit ");
System.out.println("Please select an action: ");
action = keyboard.nextInt();
}
# 1 楼答案
如果您使用的是FileWriter,请确保为要追加的第二个参数传递true