【发布时间】:2016-01-15 22:31:36
【问题描述】:
我的刽子手游戏快完成了,但我无法用这些字母替换正确猜到的字母的下划线。每当我选择正确的字母时,都会创建一个无限循环。非常感谢任何帮助。
//公共字符串短语;
//公共字符串newMask;
public boolean showLetter(String letter)
{
phrase = phrase.toUpperCase();
int pos = phrase.indexOf(letter);
if(pos != -1) { //If the letter is part of the phrase.
do {
//Letter and phrase don't change.
//Cut the "a"
pos = phrase.indexOf(letter);
//Make a new string and take the digit out.
//I must break out of the loop.
//add code here
newMask = phrase.substring(0,pos)+phrase.charAt(pos)+phrase.substring(pos);
} while (pos != -1);
setValue(mask);
} else {
return false;
}
return true;
}
【问题讨论】:
-
为什么它不会创建无限循环???
letter在循环内总是相同的。因此pos不会改变。那么控制将如何从循环中出来?不明白循环有什么用? -
循环的使用是用正确的字母替换所有必要的下划线。例如,因为字母是“All's well that ends well!”,如果我选择“e”,则所有代表“e”的下划线都更改为 e。你知道我该怎么做吗?
-
你不能使用String
replace()方法吗? -
看看
String#indexOf(int, int)。您需要从最后找到的索引 + 1 开始,否则您只是一遍又一遍地重复相同的操作。此外,newMask = ...行当前将整个掩码替换为phrase(一个字母加倍),这可能不是您想要的。 -
这里为什么需要做while循环?如果你想循环然后在函数
showLetter(String letter)上做