有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

当用户按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) 个答案

  1. # 1 楼答案

    如果您使用的是FileWriter,请确保为要追加的第二个参数传递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
    }