我目前正在用Java编写一个“Hangman”类型的游戏,但我偶然发现了一个问题。
static String word = JOptionPane.showInputDialog(null, "Enter word");
static String star = "";
public static Integer word_length = word.length();
public static Integer nrOfAttempts = 12;
public static Integer remainingAttempt = nrOfAttempts;
public static void main(String[] args) {
// String görs med lika många stjärnor som ordet har tecken
for (int i = 0; i < word.length(); i++) {
star += "_";
}
attempt();
}
public static void attempt(){
for(int o = 0; o < nrOfAttempts; o++) {
String attempt = JOptionPane.showInputDialog(null, "Enter first attempt");
if (attempt.length() > 1) {
JOptionPane.showMessageDialog(null, "Length of attempt can only be one character long");
attempt();
} else {
if (word.contains(attempt)) {
int attemptIndex = word.indexOf(attempt);
star = star.substring(0,attemptIndex) + attempt + star.substring(attemptIndex+1);
JOptionPane.showMessageDialog(null, "Hit!\nThe word is now:\n"+star);
nrOfAttempts++;
if (star.equals(word)) {
JOptionPane.showMessageDialog(null, "You've won!");
System.exit(0);
}
} else {
remainingAttempt--;
JOptionPane.showMessageDialog(null, "Character not present in chosen word\nRemaining Attempts: "+remainingAttempt);
}
}
}
JOptionPane.showMessageDialog(null, "Loser!");
}
如果我想替换“star”String
(由下划线组成的单词)中特定位置的特定字符,它只会替换匹配的第一个字符。它一遍又一遍地这样做,所以不可能获胜。
因此,“马铃薯”和“酷”之类的词语不起作用。
我想要它做的是替换所有匹配的字母,而不仅仅是它看到的第一个字母。是否可以在不创建数组的情况下执行此操作?
答案 0 :(得分:3)
以下是您在整个字符串中替换字母的方法:
int attemptIndex = word.indexOf(attempt);
while (attemptIndex != -1) {
star = star.substring(0, attemptIndex) + attempt + star.substring(attemptIndex + 1);
attemptIndex = word.indexOf(attempt, attemptIndex + 1);
}
在indexOf
的第二个版本中,提供了开始搜索的索引。这是一个+ 1,以避免再次找到相同的字母。 indexOf的文档。
请注意,使用StringBuilder
的char数组可能是一种更有效的解决方案,因为它可以避免创建许多临时字符串。
答案 1 :(得分:0)
要逐步替换所有匹配的字母,您可以使用正则表达式replaceAll(String regex, String replacement)
:String doc
例如:
String word = "potato";
String start = "______";
String attempt = "o";
start = word.replaceAll("[^"+attempt+"]", "_");
// start = "_o___o";
attempt += "t";
start = word.replaceAll("[^"+attempt+"]", "_");
// start = "_ot_to";
attempt += "p";
start = word.replaceAll("[^"+attempt+"]", "_");
// start = "pot_to";
attempt += "a";
start = word.replaceAll("[^"+attempt+"]", "_");
// start = "potato"; -> win