[英]Scanner input gets appended to textfile despite condition in while-loop
我有一個小的Java應用程序,在終端執行時將接收字符串輸入,並將這些字符串保存到文本文件中。 我有一個字符串exit
,它將提示應用程序退出。 但是,由於某種原因,盡管有while(!)
循環,但字符串exit
仍會附加到文檔中。 可能是什么問題?
try{
Scanner scanner = new Scanner(System.in);
String input = null;
while(!"exit".equalsIgnoreCase(input)){
input = scanner.nextLine();
String fileLocation = "/Users/myName/Dropbox/myDocument.txt";
FileWriter writer = new FileWriter(fileLocation,true);
writer.append(returnDate()+": ");
writer.append(input + "\n");
writer.flush();
writer.close();
}
}catch(Exception e){
e.printStackTrace();
}
認真遵循您的代碼。 您需要在下一次評估while循環條件之前 ,在循環中進行所有處理。
你有:
while(!"exit".equalsIgnoreCase(input)){
input = scanner.nextLine();
...
writer.append(input + "\n");
...
}
假設用戶鍵入“ exit”作為第一個命令,則流程為:
input
為null
。 while
條件成功。 input
,現在是“退出”。 input
(即“退出”)被寫入文件。 while
循環重新開始,條件評估,失敗,循環不會再次執行。 請注意,“退出”已寫入文件。
您將需要稍微修改一下邏輯以確保不會發生文件寫入。 這不是一種罕見的情況。 有許多解決方案取決於您的喜好。 您可以將賦值和比較合並到while
語句中:
while (!"exit".equalsIgnoreCase(input = scanner.nextLine())) {
write input;
}
您可能會有多余的檢查(對於您的簡單示例而言,這沒有意義,而且經常指示總體邏輯改進的空間):
while (input is not exit) {
read input;
if (input is not exit) write input;
}
您根本無法使用循環條件:
while (true) {
read input;
if (input is exit) break;
write input;
}
有很多方法可以修復它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.