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

时间:2014-04-11 23:22:59

标签: java file append text-files

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

  1. 玩新游戏
  2. 查看分数
  3. 退出游戏。
  4. 当用户按下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 个答案:

答案 0 :(得分:0)

如果您使用的是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
}