Results 1 to 4 of 4

Thread: Which to use?

  1. #1
    wizar is offline Member
    Join Date
    Nov 2010
    Posts
    18
    Rep Power
    0

    Default Which to use?

    If you have a sentence, and you separate it into tokens (which would be the words of the sentence in this case), how would you work with the tokens? Would you work with the original string variable?

    Here's what I mean, where this part of code is part of a method. I want to replace every 'a' in the words with an 'e':

    Java Code:
        String sentence="insart taxt hara";
        StringTokenizer words = new StringTokenizer (sentence);
        StringBuffer speech = new StringBuffer ();
        String phrase="";
        
        while (words.hasMoreTokens())
        {
          for (int x = 0; x < sentence.length(); x++)
          {
            if (sentence.charAt(x) == 'a')
            {
              sentence = sentence.replace('a', 'e');
            }
          } 
        }
        speech.append(words.nextToken());
        phrase = speech.toString();
        System.out.println(phrase);

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default

    Java Code:
    while (words.hasMoreTokens())
    {
        //...
    }
    speech.append(words.nextToken());

    Doesn't this result in some sort of runtime exception?

    ---------

    It's not really clear what you are trying to do here. If you want to replace all the 'a' characters with 'e' just use replace() once. This has nothing to do with tokenising.

  3. #3
    wizar is offline Member
    Join Date
    Nov 2010
    Posts
    18
    Rep Power
    0

    Default

    I know that I could do that, but I want to separate the sentence into words and replace the a's separately, word by word.
    My compiler's being a pain, I have to check about the error.

  4. #4
    wizar is offline Member
    Join Date
    Nov 2010
    Posts
    18
    Rep Power
    0

    Default

    My compiler is still having the same problem, it won't run. My cursor just turns into the hourglass.
    I would really like to understand this...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •