我目前正在用 Java 制作“刽子手”类型的游戏,但我偶然发现了一个问题。
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
(由下划线组成的单词)中特定位置的特定字符时,它只替换第一个匹配的字符。它一遍又一遍地这样做,所以它不可能取胜。
因此,诸如“土 bean ”和“酷”之类的词是行不通的。
我想要它做的是替换所有匹配的字母,而不仅仅是它看到的第一个字母。是否可以在不创建数组的情况下执行此操作?
最佳答案
以下是您如何对整个字符串进行字母替换:
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
的字符数组可能是更有效的解决方案,因为它可以避免创建许多临时字符串。
关于java - 替换字符串中不同位置的多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43802239/