我有一个几乎完成的程序。唯一的问题是当用户输入“exit”来杀死程序时,“exit”这个词会被写入文件“quotes.txt”的末尾。如何让程序首先检查“退出”而不是将其写入“quotes.txt”?
这是代码:
public static void main(String[] args) throws IOException {
final Formatter fo;
BufferedWriter bw = null;
BufferedReader in = new BufferedReader(new FileReader("quotes.txt"));
String input = "";
String line;
File quotesFile = new File("quotes.txt");
if (quotesFile.exists()) {
System.out.println(quotesFile.getName() + " exists.");
} else {
System.out.println("THIS DOES NOT EXIST.");
}
try {
fo = new Formatter("quotes.txt");
System.out.println("File created or found.");
} catch (Exception e) {
System.out.println("You have an error.");
}
do {
try {
Scanner kb = new Scanner(System.in);
if (!input.equalsIgnoreCase("exit")) {
System.out.println("Enter your text(Type 'exit' to close program.): ");
bw = new BufferedWriter(new FileWriter(quotesFile, true));
input = kb.nextLine();
bw.write(input);
bw.newLine();
bw.close();
System.out.println("Entry added.\n");
}
} catch (Exception e) {
System.out.println("Error.");
}
} while (!input.equalsIgnoreCase("exit"));
System.out.println("Results: ");
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
}