2017-02-27 12 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で確認できます。

終了語が入力として見つかった場合、ループを解除してユーザーからの入力を停止し、BufferedReaderScannerを閉じます。

サンプルコード: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

私はそれを考えていないために私の自己に少し失望しています...ああ。お手伝いありがとう。 –

関連する問題