编写一个程序,读取一行文本,然后用另一个单词替换一个单词

时间:2013-09-21 10:13:37

标签: java file replace printwriter textedit

在我继续讨论我的问题之前,我只是想说我对Java完全不熟悉,因为我在学校学习Java课程而对此知之甚少,我认为我喜欢这门语言,但老实说我得到了对班级的方式感到沮丧

所以我需要编写一个程序,将一首诗中的所有“你”替换为“我们”。这就是我提供的测试人员课程。我知道这是错的,我只是在猜测

Replace.java

import java.io.FileInputStream;
import java.io.File;  
import java.io.FileNotFoundException;  
import java.io.PrintWriter;

public class Replace {

    String old_poem;
    String new_poem;

    //sets the name to OldPoem for the file with the original Poem 
    //sets the name to NewPoem for the file with the converted Poem
    public Replace()
    {
        File inputFile = new File("OldPoem.txt");
        String line = in.nextLine();
    }
    // replaces "you " with "we "
    public void convert() throws FileNotFoundException
    {
        String newLine = line.replaceFirst("you", "we");
        PrintWriter out = new PrintWriter("NewPoem.txt");
        out.println(newLine);
    }

    //compares if the lines are the same in the new_poem file and in the correct file
    //one line each time
    public void same_as(String correct) throws FileNotFoundException
    {
        //stuck
    enter code here
    }
}

TextEditorTester.java

import java.io.FileNotFoundException;
public class TextEditorTester
{
 private static boolean line_change;

   public static void main(String[] args) throws FileNotFoundException
   {
      Replace poem=new Replace();
      poem.convert();
      poem.same_as("Kates.txt");     
   }
}

1 个答案:

答案 0 :(得分:1)

试试这个,

    try
            {
                String input = "";
                br = new BufferedReader(new FileReader(inputFile));
                out = new PrintWriter(outputFile);
                while ((input = br.readLine()) != null)
                {
                    if (input.contains("you"))
                    {
                        input = input.replaceAll("you", "we");

                        out.println(input);
                    }
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            finally
            {
                try
                {
                    if (br != null)
                    {
                        br.close();
                    }
                    if (out != null)
                    {
                        out.close();
                    }
                }
                catch (IOException ex)
                {
                    ex.printStackTrace();


}
        }