gpt4 book ai didi

java - 用文本文件存储和显示多个用户的信息

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:31 24 4
gpt4 key购买 nike

我正在编写一个程序,允许用户玩老虎机,然后将他们的姓名和分数存储到文本文件中。在程序开始和老虎机游戏结束时,有一个包含三个选项的菜单供用户选择:

  1. 玩新游戏
  2. 查看分数
  3. 退出游戏。

当用户按下2时,程序应该显示每场比赛的分数,而不仅仅是刚刚玩的比赛;因此,每当用户玩游戏时,他们的信息都应 append 到已有的文件 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();
}

最佳答案

如果您使用的是 FileWriter,请确保为要 append 的第二个参数传递 true。

try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("score.txt", true)));
out.println(score);
out.close();
} catch (IOException e) {
//deal with the exception
}

关于java - 用文本文件存储和显示多个用户的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23024139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com