简体   繁体   English

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

[英]Storing and displaying multiple users' information with a text file

I am writing a program which allows the user to play a slot machine, then stores their name and score to a text file. 我正在编写一个程序,允许用户玩老虎机,然后将他们的姓名和分数存储到文本文件中。 At the beginning of the program and end of the slot machine game, there is a menu of three options a user can choose from: 在程序开始和老虎机游戏结束时,有一个菜单,用户可以选择三个选项:

  1. To play a new game 玩新游戏
  2. View Scores 查看分数
  3. Exit the game. 退出游戏。

When a user presses 2, the program should show the scores of each game, not just the game just played; 当用户按下2时,程序应显示每个游戏的得分,而不仅仅是刚刚玩过的游戏; so, whenever a user plays, their information should be appended to an already existing file, score.txt . 因此,每当用户播放时,他们的信息都应附加到已经存在的文件score.txt

My problem is that whenever I try to read from this file, it only ever displays scores from the game just played. 我的问题是,每当我尝试读取此文件时,它只会显示刚刚玩过的游戏的分数。 Here is the code that runs after the game ends: 以下是游戏结束后运行的代码:

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();
}

If you are using a FileWriter make sure you pass true for the second argument to append. 如果使用的是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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM