Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: class String replaceAll does not behave as i expected

  1. #1
    Member
    Join Date
    Jul 2012
    Posts
    90
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default class String replaceAll does not behave as i expected

    The situation : I have a string and if a word is considered to be a mistake it has to be replaced by "SPELLING_MISTAKE".How do i resolve if a word is a mistake or not?I have a string array with all the correct words.So when i trace the wrong word the progam behaves good and reaches the line where the replacement is meant to be done.But no replacement is done :/ Why?What i am missing?

    package essaycorrection;
     
    public class Phrase {
     
        /**
         * **************************Variables-fields****************************
         */
        private int noOfWords;
        private String content;
        private static final String[] correctWords = {"All", "Work", "And", "No", "Play",
            "Makes", "Jack", "A", "Dull", "Boy"};
        private static final String[] wrongWords = {"Samaras", "Theodor", "George", "Kostoula",
            "Charalampos", "Pokemon", "Lapras", "Kahn", "Charizard", "Skoupi"};
     
        /**
         * **************************Constructor****************************
         */
        public Phrase(int N) {
            content = "";
            noOfWords = 1 + (int) (Math.random() * N);//numbers from [1,N]
            int select;//pick correct or wrong word
            for (int i = 0; i < noOfWords; i++) {
                select = (int) (Math.random() * 2);
                if (select == 1) {
                    content += correctWords[(int) (Math.random() * noOfWords)] + " ";
                } else {
                    content += wrongWords[(int) (Math.random() * noOfWords)] + " ";
                }
            }
            System.out.println("I just composed a phrase with content : " + content + ".");
        }
     
        /**
         * **************************Accessors****************************
         */
        public int getNoOfWords() {
            return noOfWords;
        }
     
        public String getContent() {
            return content;
        }
     
        public String[] getCorrectWords() {
            return correctWords;
        }
     
        public String[] getWrongWords() {
            return wrongWords;
        }
     
        /**
         * **************************Methods****************************
         */
        void spellCorrect() {
            String temp = "";//holds a word at the time in order to check the correctness
            char letter;
            boolean mistake;
            int i = 0;
            while (i < content.length()) {
                if ((letter = content.charAt(i)) != ' ') {
                    temp += letter;
                } else {
                    mistake = true;
                    for (int j = 0; j < correctWords.length; j++) {
                        if ((temp.compareToIgnoreCase(correctWords[j])) == 0) {
                            mistake = false;
                        }
                    }
                    if (mistake) {System.out.println("edw1 "+temp );
                        content.replaceAll(temp, "SPELLING_MISTAKE");
                    }
                    temp="";
                }
                i++;
            }
     
        }
     
        public void print()
        {
            System.out.println(content+".");
        }
    }

    in main
            Phrase p = new Phrase(5);
            p.spellCorrect();
            p.print();

    and the output
    I just composed a phrase with content : Samaras Samaras Samaras .
    edw1 Samaras
    edw1 Samaras
    edw1 Samaras
    Samaras Samaras Samaras .
    BUILD SUCCESSFUL (total time: 0 seconds)

    Also tried replaceFirst but no change in output!


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: class String replaceAll does not behave as i expected

    where is the main() method for testing the code?

    If you are only having problems with the replaceAll() method, write a short simple program that uses that method many different ways to see how the method works. All the extra logic in what you have posted does not help solving the problem learning how to use replaceAll().
    When you get the technique for using the replaceAll() method then you can work on the logic in the posted code.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: class String replaceAll does not behave as i expected

    Quote Originally Posted by Samaras View Post
    ...What i am missing?...
    replaceAll does not replace anything in the existing String (It can't, because Strings are immutable.) What it does is that it creates a brand new String with replacement as directed.

    Try the following in spellCorrect() to see what the program is seeing:
                    if (mistake) {
                        System.out.println("edw1 "+temp );
                        System.out.printf("    Before correction: <%s>\n", content);
                        content.replaceAll(temp, "SPELLING_MISTAKE");
                        System.out.printf("    After  correction: <%s>\n", content);
                    }

    Then try the following and see what happens. (Get ready to hit Ctrl-C or the "Stop" button or whatever you need to do to make a runaway program stop running away.)
                    if (mistake) {
                        System.out.println("edw1 "+temp );
                        System.out.printf("   Before correction: <%s>\n", content);
                        content = content.replaceAll(temp, "SPELLING_MISTAKE");
                        System.out.printf("   After  correction: <%s>\n", content);
                    }


    Cheers!

    Z
    Last edited by Zaphod_b; August 19th, 2012 at 10:25 AM.

  4. #4
    Member
    Join Date
    Jul 2012
    Posts
    90
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: class String replaceAll does not behave as i expected

    @Norm i wrote the lines of main that are invoke the method
    @Zaphod_b the answer was Strings are immutable ( unlike the StringBuilder Class).Hitting stop run was also needed.I am going to fix it now!Thank you both.

    PS-Zaphod_b your name is awesome ,it reminds me of Zapdos(this is a pokemon ) from when i was a kid.

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: class String replaceAll does not behave as i expected

    i wrote the lines of main that are invoke the method
    Where is the main() method for testing? I don't see where the code is that can be compiled for testing.
    Can you provide one for testing?
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Member
    Join Date
    Jul 2012
    Posts
    90
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: class String replaceAll does not behave as i expected

    Quote Originally Posted by Samaras View Post
    I am going to fix it now!
    Solved! I post it in order other people face the same problem
    void spellCorrect() {
            String temp = "";//holds a word at the time in order to check the correctness
            char letter;
            boolean mistake;
            int i = 0;
            while (i < content.length()) {
                if ((letter = content.charAt(i)) != ' ') {
                    temp += letter;
                } else {
                    mistake = true;
                    for (int j = 0; j < correctWords.length; j++) {
                        if ((temp.compareToIgnoreCase(correctWords[j])) == 0) {
                            mistake = false;
                        }
                    }
                    if (mistake) {
                        content=content.replaceAll(temp, "SPELLING_MISTAKE");
                        while ((letter = content.charAt(i)) != ' ') {
                            i++;
                        }
                    }
                    temp="";
                }
                i++;
            }
     
        }

    Quote Originally Posted by Norm View Post
    Where is the main() method for testing? I don't see where the code is that can be compiled for testing.
    Can you provide one for testing?
    Oh,i did that in order not to make you tired of reading code.I solve it now

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: class String replaceAll does not behave as i expected

    That's fine if you don't want anyone to help by compiling and testing the code.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Member
    Join Date
    Jul 2012
    Posts
    90
    Thanks
    1
    Thanked 2 Times in 2 Posts

    Default Re: class String replaceAll does not behave as i expected

    Quote Originally Posted by Norm View Post
    That's fine if you don't want anyone to help by compiling and testing the code.
    All i wanted is to make your life easier :/ I understand that i did not succeed in it.Now you told i'll keep that in mind

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: class String replaceAll does not behave as i expected

    Leaving out code that can have an impact on how the program executes doesn't make it easier to understand a problem. Seeing all of the code so there are no doubts about what else could be happening makes it easier. Since most beginners don't know what is important and what is not important, posting full code for testing is better.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. use of regular expressions in string.replaceAll
    By nesthead98 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 17th, 2012, 01:24 PM
  2. Replacing parts of a String using line.replaceAll
    By brandonSMC in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 27th, 2012, 04:07 PM
  3. [SOLVED] Error: Class,interface or enum expected
    By FJIW in forum What's Wrong With My Code?
    Replies: 10
    Last Post: September 18th, 2011, 03:08 PM
  4. .'class' expected - what to do?!?! URGENT
    By Rads23 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: August 17th, 2011, 06:05 PM
  5. Java applet that can behave like dekstop app?
    By cowcool in forum Java Theory & Questions
    Replies: 5
    Last Post: May 28th, 2011, 01:16 PM