1

I am trying to make a Hangman code in Java. I have a interface class with random words, that each time the program runs I pick a word from there. Now I made a string for control that copy's the value of the first string and I want to change all the letters with "_". The problem is that from what I found if I use replace all I can change only a letter. I tried to use it with a for to go throw all the letters in the alphabet but I could't use the initialisation in replace. It asked a letter. Is there a way (or a method) that I can change my word?

public class Main {
    static String rdword;
    static int n;

    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    Random rd = new Random();

    n = rd.nextInt(3000);
    rdword= EnWords.words[n];
    String control = rdword;

    for (char i = 'a'; i < 'z'; i++ ) {
        control .replace (i, "_");
    }
}
3
  • Why not replaceAll? Commented Sep 5, 2018 at 18:32
  • One major problem with your code is that String is immutable, so replace cannot update the string, and instead returns the new string value, but your code doesn't use the return value. Your code would work if you changed statement to control = control.replace(i, '_');. Note also how the second parameter was changed to a char, so the replace(char oldChar, char newChar) version of the method is called. Commented Sep 5, 2018 at 19:13
  • Why not just make a new string of the appropriate length made up of all underscores? I'm not a Java guy, but in c# you could do new string('_', control.Length). I imagine something similar exists in Java. Commented Sep 5, 2018 at 19:46

1 Answer 1

1

Simply use regex instead of for loop like below snippet:

control = control.replaceAll("[a-z]", "_")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.