我的这段代码中有一个错误。调试器表明原因是这行代码 char chr = getSecretWord.charAt(i);
此代码的作用是查找 userInput
之间的匹配项和secretWord
。我有for loop
逐一检查secretWord字母的长度,如果有字母匹配则返回true。如果不是,则返回 false...但是当它应该返回 false 时程序崩溃...我猜这是这一行的内容,但不知道到底是什么 getSecretWord.charAt(i);
private boolean isMatchingSecretWord(String userInput)
{
String secretWord = "";
String getSecretWord = getSecretWord();
for (int i = 0; i <= getSecretWord.length();i++)
{
char chr = getSecretWord.charAt(i);
secretWord = ""+chr;
if (secretWord.equals(userInput))
{
println("is true");
return true;
}
}
return false;
}
作为旁注,我对这段代码所做的操作是否正确,将 getSecretWorld() 方法分配给字符串,以便我可以使用字符串方法 length()
?
String getSecretWord = getSecretWord();
for (int i = 0; i <= getSecretWord.length();i++)
调试代码:
Exception in thread "Thread-4" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:686)
at Hangman.isMatchingSecretWord(Hangman.java:49)
at Hangman.userInput(Hangman.java:34)
at Hangman.run(Hangman.java:20)*
最佳答案
for (int i = 0; i <= getSecretWord.length(); i++)
应该是:
for (int i = 0; i < getSecretWord.length(); i++)
// ^^^
// see here
n
字符串(或 n
元素数组)的有效索引为 0
到 n-1
包含在内。
因此,如果您的 secret 词是 xyyzy
,则有效索引为 0 到 4。您的原始循环将 i
设置为 0 到 5 进行迭代,因此出现了问题。
但是其中似乎有很多不必要的代码,而您可以使用简单的代码。
首先,我会消除一个困惑的根源 - 函数名称听起来像用户输入和 secret 单词必须完全匹配,而您的评论表明不然:
Thanks, this works. But the reason for the loops is that the user enters one letter, I want to see if that letter is within the SecretWord. (it´s a hangman game).
在这种情况下,您只想查看 secret 单词中是否存在单个字符。我会更改函数名称以适应,即使这样,也可以用更少的代码来完成:
private boolean isInSecretWord (String userInput) {
String secretWord = getSecretWord();
return secretWord.contains(userInput);
}
关于Java:使用字符串 charAt 方法的 for 循环崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12469385/