Search code examples
javastringchars

Changing Certain Chars in A String


I'm a beginner programmer and I'm trying to make a very simple version of Hangman. I'm having so problem with my code. This is the portion of code I'm having a problem with:

        for(int i = 0; i <= wordLength - 1; i++ ) {

            if (letter == theWord.charAt( i )) {

                onemore=i+1;
                System.out.println("This letter matches with letter number " + onemore + " in the word.");
                ***displayWord.charAt(i)=letter;***
                System.out.println("The word so far is " + displayWord);
            } 

        }

The part I'm getting an error with has 3 asterisks on either side of it.

displayWord is a String and letter is a char.

Netbeans tells me:

unexpected type
  required: variable
  found:    value

I have no idea what the problem is.


Solution

  • Basically, Java Strings are immutable, that is, there contents can't be changed.

    You'd be better of using a StringBuilder.

    String theWord = "This is a simple test";
    char letter = 'i';
    char changeTo = '-';
    
    StringBuilder displayWord = new StringBuilder(theWord);
    
    int i = theWord.indexOf(letter);
    if (i != -1) {
        System.out.println("This letter matches with letter number " + (i + 1) + " in the word.");
        displayWord.setCharAt(i, changeTo);
    
        System.out.println("The word so far is " + displayWord);
    }
    
    System.out.println(displayWord);
    

    This results in:

    This letter matches with letter number 3 in the word.
    The word so far is Th-s is a simple test
    This letter matches with letter number 6 in the word.
    The word so far is Th-s -s a simple test
    This letter matches with letter number 12 in the word.
    The word so far is Th-s -s a s-mple test
    Th-s -s a s-mple test
    

    Now the short version might look something like

    String displayWord = theWord.repace(letter, changeTo);