This discussion is archived
3 Replies Latest reply: Mar 16, 2008 4:17 PM by 807591 RSS

Problems with StringBuilders and Replacing Chars

807591 Newbie
Currently Being Moderated
I need to generate a password of random letters and numbers, I've been successful so far, but what I need to do is take the password I generated, delete one character, add a number to the end. Once that's done, I need to search the password for the letters L and O and replace them with underscore.

When I call makeBetterPassword() - It outputs : 4 random letters and a bunch of squares

When I call makeEvenBetterPassword() - I get the following error.
Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1

Here's my code - Any help would be greatly appreciated :)

   
public StringBuilder makeBetterPassword()
   {      
       makeBetterSB.setLength(passLength -1);
        makeBetterSB.append(randNumber);
      if(noise.nextBoolean() == true)
      {
         makeBetterSB.reverse();
      }
      return makeBetterSB;
   }
   
   public void makeEvenBetterPassword()
   {
      int indexStart = 0;
      int indexEnd = 0;
      
      for(int i = 0; i < makeBetterSB.length(); i++)
      {
         indexStart = makeBetterSB.indexOf("l", 0);
         indexEnd = indexStart +1;
         makeBetterSB.replace(indexStart, indexEnd, "_");
      }
   }
  • 1. Re: Problems with StringBuilders and Replacing Chars
    807591 Newbie
    Currently Being Moderated
    the3rdhero wrote:
    I need to generate a password of random letters and numbers, I've been successful so far, but what I need to do is take the password I generated, delete one character, add a number to the end. Once that's done, I need to search the password for the letters L and O and replace them with underscore.

    When I call makeBetterPassword() - It outputs : 4 random letters and a bunch of squares
    squares: you have numbers in there that don't correspond to ASCII characters. You may want to limit the range of random numbers allowed.
    >
    When I call makeEvenBetterPassword() - I get the following error.
    Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    So the original password doesn't have any "l" characters and returns -1. You have to allow for this.
  • 2. Re: Problems with StringBuilders and Replacing Chars
    807591 Newbie
    Currently Being Moderated
    How exactly?
    I'm still learning Java, aint got the best knowledge :(
  • 3. Re: Problems with StringBuilders and Replacing Chars
    807591 Newbie
    Currently Being Moderated
    the3rdhero wrote:
    How exactly?
    I'm still learning Java, aint got the best knowledge :(
    How what?

    To limit the range of random numbers use the method of Random that takes the upper limit as a paramater.

    To handle indexOf returning a -1 then use an if statement that only does something if the value returned is not -1.