2013-04-01 50 views
0

我有一個幾乎完成的程序。唯一的問題是當用戶輸入「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); 
    } 

} 
} 
+0

而不是一個do-while循環做一個while循環。你也不需要每次在循環中創建一個新的BufferedWriter。此外,輸入可能包含空格和/或換行符,因此您應該嘗試比較input.trim()。 – HectorLector

回答

1

檢查輸入是其寫入文件之前什麼。

  System.out.println("Enter your text(Type 'exit' to close program.): "); 
      bw = new BufferedWriter(new FileWriter(quotesFile, true)); 
      input = kb.nextLine(); 
      if(!input.equalsIgnoreCase("exit")) { 
       bw.write(input); 
       bw.newLine(); 
       bw.close(); 
       System.out.println("Entry added.\n"); 
      } 
     } 
+0

這工作完美!謝謝! – user1422051

2

您只能實現一次掃描儀和書寫器的實例。問題的關鍵在於您在測試後檢查輸入。請注意,您重複測試:if中的一個,while中的另一個。我建議你這個算法:

Scanner kb = new Scanner(System.in); 
input = kb.nextLine(); 

while (!input.equalsIgnoreCase("exit")) { 
    try { 
     System.out.println("Enter your text(Type 'exit' to close program.): "); 
     bw = new BufferedWriter(new FileWriter(quotesFile, true)); 
     bw.write(input); 
     bw.newLine(); 
     bw.close(); 
     System.out.println("Entry added.\n"); 
    } catch (Exception e) { 
     System.out.println("Error."); 
    } 
    input = kb.nextLine(); 
} 

請注意,do...while不能最好地響應您的需求。

+0

感謝您提供另一種方式,而不是使用do-while。我聽說過使用do-while並不是最好的做法,如果你能避免它。 – user1422051

+0

不客氣!只要照顧你的結果腳本,我看到你接受了以前的回答,但檢查你如何打開/關閉你的作家:當你打開一個時,應該(必須)關閉它。一個好的做法是在你的'catch'後面把'bw.close();'放在'finally'塊中。更重要的是,您可以在循環之外打開Writer並僅在關閉之後關閉它。祝你好運! – blint