我有一個JOptionPane,提示用戶提問並接收一個隨機生成的答案。我「米想寫記錄了所有的問題和答案一個文件,但FileWriter的只記錄了最後一個問題&答案這裏是我的代碼:FileWriter只在循環中寫入最後一行。需要它寫一個所有輸入的日誌
import javax.swing.JOptionPane;
import java.util.Random;
import java.io.*;
public class Magic8Ball {
public static void main(String [] args)throws Exception {
final String QUIT = "quit";
Random rand = new Random();
int max = 7;
int min = 0;
int randomNum;
FileWriter fw = new FileWriter("fortune.txt");
PrintWriter pw = new PrintWriter(fw);
BufferedWriter out = new BufferedWriter(fw);
String[] answers = new String[8];
String question = JOptionPane.showInputDialog(" Enter a question or " + QUIT + " to exit ");
Create8Ball(answers);
while (!question.equals(QUIT)) {
randomNum = rand.nextInt((max - min) + 1) + min;
System.out.println(answers[randomNum]);
pw.println("Question: " + question);
pw.println("Fortune Response: " + answers[randomNum]);
question = JOptionPane.showInputDialog(" Enter a question or " + QUIT + " to exit ");
}
pw.close();
System.exit(0);
}
public static void Create8Ball(String answers[]) throws Exception
{
FileReader fr = new FileReader ("answers.txt");
BufferedReader br = new BufferedReader (fr);
String dog = null;
int cat = 0;
while ((dog = br.readLine()) != null)
{
answers[cat] = dog;
cat++;
}
//close the input file
br.close();
}
}
謝謝!我拿出了BufferedWritter並添加了pw.flush();在pw.close()之前;似乎在做這項工作。 – user3797287