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 :(
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.