0

こんにちは、詩を含むファイルを読み取るコードを作成しようとしています。次に、すべての行の最初の「you」を「we」に変更します。replaceFirst()、replace()、replaceAll(); を使用しようとしています。ただし、何かを置き換えるのに機能したものは1つもありません。

 import java.io.*;
import java.util.Scanner;//imports

public class TextEditorTester 
{
    private static boolean line_change;

   public static void main(String[] args) throws FileNotFoundException
   {
       String line = "";
       File inFile = new File("OldPoem.txt");
       Scanner in = new Scanner(inFile);
       PrintWriter out = new PrintWriter("NewPoem.txt");
       while(in.hasNextLine()){
           line = in.nextLine();
           line.replace("you", "we");
           out.println(line);
       }
       out.close();
       File newFile = new File("NewPoem.txt");
       Scanner newOne = new Scanner(newFile);
       System.out.println(newOne.nextLine());
       System.out.println("Expected: Have we ever tried to enter the long black branches of other lives");
   }
}
4

2 に答える 2

3

このreplaceメソッドは新しい行を返します。呼び出したオブジェクトを変更することはできません。だから試してください:

line = line.replace("you", "we");
于 2013-09-16T04:05:47.787 に答える
2

文字列は Java では不変です。つまり、それらは決して変わらないということです。呼び出しているメソッドは新しい文字列を返します。それらをどこかに保存する必要があります。

line = line.replace("you", "we");

文字列に作用するメソッドについて質問する前に、Java の文字列に関する Javadoc を調べてください。すべてはここで説明されています

于 2013-09-16T04:06:05.683 に答える