Java String.replaceFirst()问题
嗨,我正在尝试编写代码来读取包含一首诗的文件。然后,它会将每行中的第一个“you”改为“we”。我一直在尝试使用replaceFirst()、replace()、replaceAll();然而,没有一个能取代任何东西Java String.replaceFirst()问题,java,replace,printwriter,Java,Replace,Printwriter,嗨,我正在尝试编写代码来读取包含一首诗的文件。然后,它会将每行中的第一个“you”改为“we”。我一直在尝试使用replaceFirst()、replace()、replaceAll();然而,没有一个能取代任何东西 import java.io.*; import java.util.Scanner;//imports public class TextEditorTester { private static boolean line_change; public st
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");
}
}
replace
方法返回新行,它不能修改调用它的对象。因此,请尝试:
line = line.replace("you", "we");
replace
方法返回新行,它不能修改调用它的对象。因此,请尝试:
line = line.replace("you", "we");
字符串在Java中是不可变的。这意味着他们永远不会改变。您正在调用的方法返回新字符串。你需要把它们保存在某个地方
line = line.replace("you", "we");
在询问有关作用于字符串的方法的问题之前,您应该参考Java文档中关于字符串的内容。一切都解释清楚了字符串在Java中是不可变的。这意味着他们永远不会改变。您正在调用的方法返回新字符串。你需要把它们保存在某个地方
line = line.replace("you", "we");
在询问有关作用于字符串的方法的问题之前,您应该参考Java文档中关于字符串的内容。一切都解释清楚了