我有一個幾乎完成的程序。唯一的問題是當用戶輸入「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);
}
}
}
而不是一個do-while循環做一個while循環。你也不需要每次在循環中創建一個新的BufferedWriter。此外,輸入可能包含空格和/或換行符,因此您應該嘗試比較input.trim()。 – HectorLector