Tudor B
Tudor B

Reputation: 11

String Replace Java

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, "_");
    }
}

Upvotes: 1

Views: 148

Answers (1)

aminography
aminography

Reputation: 22832

Simply use regex instead of for loop like below snippet:

control = control.replaceAll("[a-z]", "_")

Upvotes: 1

Related Questions