Question

Before I move on to my question, I just wanna say that I'm completely new to Java and know little about it as I'm taking Java classes in school and I think I love the language but to be honest I got frustrated by the way the class is

So I need to write a program that will replace all the "you" to "we" in a poem. This is what I have with a tester class provided. I know it's wrong I'm just guessing

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");     
   }
}
Was it helpful?

Solution

Try this,

    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();


}
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top