1
public class Main {

    public static void main(String[] args) throws Exception {
        String name = "eric";
        String nameForYou = name.replaceAll(".","*");
        String afterGuess="";
        System.out.println("Guess my name: "+nameForYou+" "+name.length());
        String yourguess = "c";
        for (int i=0;i<name.length();i++) {
            if ((yourguess.charAt(0) == name.charAt(i))){
               afterGuess = nameForYou.replace(nameForYou.charAt(i),yourguess.charAt(0));
            }
        }
        System.out.println(afterGuess);
    }
}

I want output as:

Guess my name: **** 4
***c

I don't want it to replace all the "*"

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Swapnil
  • 43
  • 9

1 Answers1

0

Your strategy does not work, because replace replaces the first character that it finds, which is not necessarily the character in the right position.

Since Java String is immutable, a better approach for your replacement code should be to make a char array of the appropriate length, and convert it to String only for printing:

String name = "eric";
char[] nameForYou = name.replaceAll(".","*").toCharArray();
System.out.println("Guess my name: "+new String(nameForYou)+" "+name.length());
String yourguess = "c";
for (int i=0;i<name.length();i++) {
    if ((yourguess.charAt(0) == name.charAt(i))){
        nameForYou[i] = yourguess.charAt(0);
    }
}
System.out.println(new String(nameForYou));

Java arrays are mutable, so you have direct control over characters at a specific index. You could also use StringBuilder if you prefer not to deal with arrays directly.

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