0

How would I save the secretNumber to a text file multiple times? As opposed to just that last time that I ran the program. Thanks to all who have helped.

     import java.io.PrintStream;

public class Recursion {
public Recursion() {}

public static void main(String[] args) {
int secretNumber = (int)(Math.random() * 99.0D + 1.0D);
java.util.Scanner keyboard = new java.util.Scanner(System.in);
int input;

do {
  System.out.print("Guess what number I am thinking of (1-100): ");
  input = keyboard.nextInt();
  if (input == secretNumber) {
    System.out.println("Your guess is correct. Congratulations!");
  } else if (input < secretNumber)
  {
    System.out.println("Your guess is smaller than the secret number.");
  } else if (input > secretNumber)
  {
    System.out.println("Your guess is greater than the secret number."); }
 } while (input != secretNumber);

 File output = new File("secretNumbers.txt");
  FileWriter fw = null; //nullifies fw

  try {//Text File Creating
     fw = new FileWriter(output);
     BufferedWriter writer = new BufferedWriter(fw);
     //FOURTH COMPETENCY: fundamentals of Characters and Strings
     writer.write(String.valueOf(saveNum));
     writer.newLine();//adds a new line to the .txt file

     System.out.println("The secret number has been saved");

     writer.close(); 
  }
}

2 Answers2

0

Use new FileWriter(output, true);. The second argument true specifies that, instead of overwriting the entire file, you keep the old contents of the file and append the new content to the end of the file instead.

Sync
  • 3,571
  • 23
  • 30
0

Currently your code will cause the file to be overwritten each time it is run. In order to continue adding numbers to the file on each run instead, you need to append to the file.

To do this, all you have to do is enable append mode for the FileWriter when you create it. You can do this by passing true as the second argument to the constructor like so:

fw = new FileWriter(output, true);
PseudoPsyche
  • 4,332
  • 5
  • 37
  • 58