java多个随机整数保存到txt文件

时间:2017-05-09 23:52:32

标签: java

如何将secretNumber多次保存到文本文件中?而不是上次我运行该程序。感谢所有帮助过的人。

     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 个答案:

答案 0 :(得分:0)

使用new FileWriter(output, true);。第二个参数true指定,不是覆盖整个文件,而是保留文件的旧内容,并将新内容添加到文件的末尾。

答案 1 :(得分:0)

目前,您的代码将导致文件在每次运行时被覆盖。为了在每次运行时继续向文件添加数字,您需要附加到文件。

要做到这一点,您所要做的就是在创建FileWriter时为其启用附加模式。您可以将true作为第二个参数传递给构造函数,如下所示:

fw = new FileWriter(output, true);