Not able to dynamically update a text file to keep track user wins or losses in Wordle game in JAVA

Viewed 43

OK, I designed a Wordle Game, at the end of game I want to keep track of users performance, I want to create a file called totalScores to store two number - the number of wins and losses. At the end of each game, I want to update this file and display the user's total number of wins and losses.

my String in totalScores is: User Total Wins: 0 User Total Losses: 0 so say if I win, this file should be updated into User Total Wins: 1 User Total Losses: 0 to keep track the score. However, after I won, my file been changed into Total User Win: 0 Total User Losses: 0Total User Win: 1 Total User Losses: 1.

public static void updateTestScore(int count) {
        String filename = "./TotalScores";
        try {
            FileWriter outfile = new FileWriter(filename, true);
            BufferedReader br  = new BufferedReader(new FileReader(filename));
            String line;
            int totalLosses;
            int totalWins;
            if (count == 6) {
                while ((line = br.readLine())!= null) {
                    String[] values = line.split(" ");
                    totalLosses = Integer.parseInt(values[7]);
                    totalLosses++;
                    String newString = line.replace(values[7], String.valueOf(totalLosses));
                    outfile.write(newString);
                }
            } else {
                while ((line = br.readLine()) != null) {
                    String[] values = line.split(" ");
                    System.out.println(Arrays.asList(values));
                    totalWins = Integer.parseInt(values[3]);
                    totalWins = totalWins + 1;
                    System.out.println(String.valueOf(totalWins));
                    String newString = line.replace(values[3], String.valueOf(totalWins));
                    outfile.write(newString);
                }
            }

            System.out.println("file successfully written");
            outfile.close();
        } catch (IOException ex) {
            System.out.println("Unable to edit the file");
            System.exit(-1);
        }
    }
0 Answers
Related