1

The string "displayed" are filled with * and its just as long as the string "secret". and secret is a word from an array.

public void replace(String input)
    {

        for (int j = 0; j < displayed.length(); j++)
        {
           if (input.charAt(0) == secret.charAt(j))  
           {
             displayed1 = displayed.replace(secret.charAt(j), input.charAt(0));

            //System.out.print(input.charAt(0) == secret.charAt(j) ? input.charAt(0) : "*");
           }
        }

        System.out.println(displayed1);

when i run this its gives me only *, it doesnt replace the * with the input. but if let print it, it replaces it..

im fairly new at programming, so it might be a stupid little thing as allways, but i cant find it :(

Rustam
  • 6,485
  • 1
  • 25
  • 25
  • 3
    I think you misunderstand the `String.replace` method. Given 2 parameters, it finds all the occurrences of the first character in the string, and replaces them with the second character. But this string only has "*" inside it. It doesn't have any character from `secret`. So it doesn't replace anything. It only replaces a character if it exists inside of it. – RealSkeptic Oct 25 '14 at 10:39
  • Ofcourse..stupid me :( it cant be done like this, i need to rethink :) – Jimmy Lillegaard Oct 25 '14 at 10:41
  • 1
    Replacing whole text with * if u dont want to reveal the value, Use no of * to represent the string e.g. User will be **** and show if thr string if user clicks button or something – Vighanesh Gursale Oct 25 '14 at 11:00

1 Answers1

1

When secret.charAt(j) is equal to input.charAt(0), the call of displayed.replace cannot possibly have any effect, because you are replacing a character with the same character. Say, secret.charAt(j) is 'x'; then your call is equivalent to

displayed1 = displayed.replace('x', 'x');

which is equivalent to displayed1 = displayed, and is definitely not what you want to do.

Moreover, displayed consists of asterisks, so the letter from secret.charAt(j) cannot even be there. What you probably want is to compose your string character by character, rather than using a sequence of repeated replacements:

char[] chars = displayed;
for (int j = 0; j < displayed.length(); j++) {
    if (input.charAt(0) == secret.charAt(j)) {
        chars[j] = secret.charAt(j);
    }
}
displayed = new String(chars);
System.out.println(displayed);

The code above uses a character array to change the string. You could also use StringBuilder, a mutable string object, to achieve the same effect.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523