[英]String Replace Java
I am trying to make a Hangman code in Java.我正在尝试用 Java 制作 Hangman 代码。 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.问题是,如果我使用 replace all,我发现我只能更改一个字母。 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.我尝试将它与 for 一起使用以抛出字母表中的所有字母,但我无法在替换中使用初始化。 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, "_");
}
}
只需使用正则表达式而不是像下面的代码段那样的循环:
control = control.replaceAll("[a-z]", "_")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.