2017-02-27 54 views
0

我試圖通過讀取用戶的輸入,直到達到某個終止符序列,但我無法弄清楚如何讓它終止,在控制檯中具有相應的文本框。將多行用戶輸入寫入文件

這裏是應該讀取輸入並將其寫入到文件的代碼:

try { 
    out = new BufferedWriter(new FileWriter("outagain.txt"); 
    userInput = new Scanner(System.in); 

    String input; 
    while ((input = userInput.nextLine)) != null) { 
     out.write(input); 
     out.newLine(); 
     input = null; 
    } 
} finally { 
    if (userInput != null) 
     userInput.close(); 
    if (out != null) 
     out.close(); 

有一些方法我可以捕捉來自用戶的轉義「碼」(即他們寫「:END」哪個突破了循環)還是有另一種方式來做到這一點?

預先感謝您。

+0

是的,你可以通過設置,比如'一些終止字做到這一點。 –

+0

那我該怎麼做呢?我試過了,但循環不會終止。 –

回答

1

您可以通過比較每個輸入行與特定的終止字來完成。 假設終止字是:END,那麼我們可以用termination word檢查每個輸入行。

如果我們發現終止字作爲輸入,我們將打破循環並停止接受來自用戶的輸入並關閉BufferedReader以及。

示例代碼:END`:

try 
    { 
     out = new BufferedWriter(new FileWriter("outagain.txt")); 
     userInput = new Scanner(System.in); 

     String input = userInput.nextLine(); //Store first input line in the variable 
     String Termination_Word = ":END"; 
     while(!input.equals(Termination_Word)) //Everytime Check it with the termination word. 
     { 
      out.write(input);     //If it isnot a termination word, Write it to the file. 
      out.newLine(); 
      input=userInput.nextLine();   //Take other line as an input. 
     } 
    } 
    finally 
    { 
     if (userInput != null) 
      userInput.close(); 
     if (out != null) 
      out.close(); 
    } 
+0

因爲沒有想到......我很好,所以我有點失望。感謝您的幫助。 –