0

I am having a hard time figuring out how to overwrite to the same file right after reading it. The point of this program is to display the value of the previous high score while the new record score gets stored so I can keep comparing them for future game sessions.

I have already added throws IOException after the main method header and I have already initialized totalScore and highScore (both are doubles). I also made sure to write 0.0 to the "score.txt" file so it has something to compare to for the first game session.

But the code keeps deleting the 0.0 value which was already written into the file and it doesn't display any of the text from the if-else statement. However, without the FileWriter it works just fine, it doesn't delete the current value and it does display the text. My only problem is trying to figure out how to overwrite the file by using FileWriter without disrupting the rest of the code like this one.

import java.util.Scanner;
import java.io.*;

public class Game
{  
   public static void main(String[] args) throws IOException
   {     
      // (highScore and netGain already initialized after main method header)
      // (The code prior to opening the file is the game itself)

      // Opens a file for new record gains
      PrintWriter pw = new PrintWriter("score.txt");
      File file = new File("score.txt");
      Scanner read = new Scanner(file);
      
      // Reads the previous net gain and determines high score
      while(read.hasNext())
      {
         highScore = read.nextDouble();
         
         if(totalScore > highScore)
         {
            System.out.print("\n******RECORD SETTING WIN******");
            System.out.print("\nThe previous record gain was $" + highScore);
            pw.print(totalScore);
            pw.close();
         }
         else
            System.out.print(" ");
      } 
      read.close();
   }
}
Rachel
  • 1
  • 1

0 Answers0