-3

If I have a string that stores an answer to a question and a for loop used to conceal the answer with underscores, is it possible to replace a character in the string answer with the user's guess and reveal it or to somehow alter the string answer to reveal only the user's right guess? Here is part of my code:

String answer = "December"; // this is the phrase i want hidden with 
//underscores
for loop( int i = 0; i < answer.length(); i++){
System.out.println("_"); // hides phrase with underscores
System.out.print("What is your guess for this round?");
String userGuess = console.next();
char ch = answer.charAt(i);
if (userGuess.indexOf(ch) != -1) { // if it is present in phrase then reveal
// then reveal that letter
Idos
  • 15,053
  • 14
  • 60
  • 75
JohnnyV
  • 1
  • 2
  • 2
    What's the problem here? I mean, String is immutable so you would probably want to use `StringBuilder`, but other than that I'm sure you can handle this. – Idos Jul 11 '18 at 18:43
  • well, I'm trying to make a new string that will copy the answer string but reveal the user's guess. So for example, user guesses e, then the new string will print out the old string just with the e's revealed – JohnnyV Jul 11 '18 at 18:47
  • 1
    Possible duplicate of [How do I replace a character in a string in Java?](https://stackoverflow.com/questions/1234510/how-do-i-replace-a-character-in-a-string-in-java) – Luca Cappelletti Jul 11 '18 at 20:16

1 Answers1

4

Yes and no. Strings are immutable so you can't actually change them. What you normally do is make a copy with the new character. So something like this.

public String replace( String s, char c, int index ) {
  return s.substring( 0, index ) + c + s.substring( index+1, s.length() );
}

Although that needs error (range) checking.

A probably better method though is to use a StringBuilder which is basically a mutable string.

public String replace( String s, char c, int index ) {
  StringBuilder sb = new StringBuilder( s );
  sb.setCharAt( index, c );
  return sb.toString();
}
markspace
  • 10,621
  • 3
  • 25
  • 39
  • nice suggestion. just keep a maskedAnswer variable that is a StringBuilder and setCharAt whenever a letter is revealed. – Patrick Parker Jul 11 '18 at 19:03
  • Yes, the OP would have to keep the original string hidden so that they can compare guesses, and show a second string with underscores to the user. They'd also have to account for lower or upper case letters somehow (it would probably be unfair to allow a user guess of 'a' to not also match a capital 'A'), and they'd have to detect when the underscore string has no more underscores and the game is won. – markspace Jul 11 '18 at 19:06