#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    1
    Rep Power
    0

    Creating a replaceAll() method with loops and character classes.


    I have an assignment in which I need to write a method with the following syntax:

    int Replacementcount = replaceWord(String fileName, String newFileName, String word, String newWord)

    Where:
    fileName = file to read from
    newFileName = file to save the new copy with replacements made
    word = the string of characters to be replaced
    newWord = the string of characters to be used at the replacement

    I have tried the following code:
    Code:
    package hwproj4;
    import javax.swing.JOptionPane;
    import java.util.Scanner;
    import java.io.*;
    
    public class HWproj4 
    {
    
        public static void main(String[] args) throws FileNotFoundException
        {
            //Function Tests
            System.out.println(replaceWord("windhover.txt", "windhover2.txt", "abc", "CBA"));
        }
        
        
        
        
        public static int replaceWord(String fileName, String newFileName, String word, String newWord) throws FileNotFoundException
        {
                Scanner FileInformation = new Scanner(new File(fileName));
                PrintStream output = new PrintStream(new File(newFileName));// Creates a new file with a printstream in order to handle printing functions. (printline, ect)
                int ReplacementCounter = 0;// Creates a replacement counter
                // Creates a new file with a printstream in order to handle printing functions. (printline, ect)
            
                //Create a loop to loop through every character
                        //Find instance of word by comparing character by character
                        //Delete instance of word
                        //Insert newWord at specified point
                        //Add 1 to replacement counter
                
                
                while (FileInformation.hasNextLine())
                // while the input1 has a next line
                {
                    //Get the individual line of text and store it in CurrentLine
                    Scanner lineInput = new Scanner(FileInformation.nextLine());
                    StringBuilder CurrentLine = new StringBuilder(lineInput.nextLine());
                    int MatchedCharCounter = 0;
                    
                    
                    
                    //System.out.println(CurrentLine);
                    //Loop through and find the occurances of the word
                    for (int i = 0; i<CurrentLine.length(); i++)
                    {
                        //System.out.println(i);
                        // If the first letter (reguardless of case) is found, continue
                        if (Character.toLowerCase(CurrentLine.charAt(i)) == Character.toLowerCase(word.charAt(MatchedCharCounter)) )
                        {
                            int BeginningPos = i;
                            i++; // Add one to the index to move to the next letter
                            MatchedCharCounter++; // Add one to the matched character count
                            while(Character.toLowerCase(CurrentLine.charAt(i)) == Character.toLowerCase(word.charAt(MatchedCharCounter)))
                                    {
                                        
                                        MatchedCharCounter++; // Increment the matched character counter
                                        if (MatchedCharCounter == word.length()) // if the counter is the same as the length, delete at the specified position
                                        {
                                            for (int j=0; j<word.length(); j++)
                                                CurrentLine.deleteCharAt(BeginningPos);
                                            CurrentLine.insert(BeginningPos, newWord);
                                            i = BeginningPos + newWord.length(); // Position the index at the position AFTER the inserted word so it does not recheck the word
                                            //System.out.println(i);
                                            ReplacementCounter++;// add one to the replacement counter after replacement
                                            MatchedCharCounter = 0; // Reset the matched counter after finished
                                            
                                        }
                                        else
                                        {
                                            //if (i < CurrentLine.length()-1)
                                                i++;
                                        }
                                        
                                        
                                        
                                    }                        
                            }
                        }
                          System.out.println(CurrentLine);
                          
                }        
            return ReplacementCounter;
        }
        
    }
    This works for bits and pieces, but there is some obvious errors. I was just printing each formatted line in the output window instead of actually writing it to a new file, which I will do later.

    The part I am having trouble with seems to be at this point:
    Code:
    if (MatchedCharCounter == word.length())
    {
    ...
    }
    If I place the text to be replaced at the end of a line, it gives an out of range error for the character at that index and for some reason my first line is off by 1 character only after the first line...

    This was the text in the file I was using to debug:
    Code:
    needlein abc ahaystack.abc.fjhds
    !needleinahaystackabc
    jhdjas321abc123kljfkljfsdkljfds
    abcjdsfhkdsj
    kljfsdabcabcabcjdadsfdskj
    First line: test replacement next to spaces and punctuation. [First instance is replaced, second is replaced, but translated 1 character to the right, making the wrong replacement]
    Second line: test at the end of the line [Throws out of range error]
    Third line: tests inside a line [replacement is translated 1 character to the right]
    Fourth Line: test at the beginning of the line [works?]
    Fifth line: tests with cases directly after one another [stuck inside a loop? The code doesn't end]

    It's obvious my index counter must be wrong somewhere in the inner if statement, but I can't see how to fix it. Can someone please point me in the right direction here?
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,696
    Rep Power
    347
    Have you tried debugging the code by adding some println statements to print out the values of the program's variables as it executes? If you see what the computer sees you should be able to change the logic so there isn't an error.

IMN logo majestic logo threadwatch logo seochat tools logo