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, "_");
}
}
replaceAll?Stringis immutable, soreplacecannot 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 tocontrol = control.replace(i, '_');. Note also how the second parameter was changed to achar, so thereplace(char oldChar, char newChar)version of the method is called.new string('_', control.Length). I imagine something similar exists in Java.