我正在尝试比较两个字符,但在StringOutOfBoundException
行收到char E = guesstwo.charAt(C)
。我该如何解决这个问题?
相关代码如下:
class Hangman{
public static void main(String args[]) {
String guessedwords = "";
Scanner keys = new Scanner(System.in);
String phrase = keys.nextLine();
int guesslim = keys.nextInt();
String guess = keys.next();
//phrase length for guessing & StringBuilder to allow modifications
StringBuilder phrasetwo = new StringBuilder(phrase);
StringBuilder guesstwo = new StringBuilder(guess);
for (int i = 0; i < phrasetwo.length(); i++) {
guessedwords += " _";
}
//loop runs through all characters
for (int i = 0; i < phrasetwo.length(); i++) {
char d = phrasetwo.charAt(i);
char e = guesstwo.charAt(i);
...
}
}
}
答案 0 :(得分:0)
String数组基于0。 length()返回数组的大小,但数组的最后位置是长度减去1。您必须在for。
的条件部分使用“&lt; =”“&lt; =”这里。
for(int C = 0; C <= phrasetwo.length(); C++){
char D = phrasetwo.charAt(C);
char E = guesstwo.charAt(C);
//if statement compares two characters
if(E == D){
System.out.println("That is a correct. Please guess again");
guesstwo = keys.next();
goodcount++;
}
答案 1 :(得分:0)
在以下代码中:
//loop runs through all characters
for (int i = 0; i < phrasetwo.length(); i++) {
char d = phrasetwo.charAt(i);
char e = guesstwo.charAt(i);
...
}
i
获取0
到phrasetwo.length - 1
的值。然后,它会引用i
和phrasetwo
中位置guesstwo
处的字符。如果phrasetwo
长于guesstwo
,那么发生错误的语句将尝试引用字符串末尾的字符。因此错误。