将stringbuilder转换为字符时的StringOutofBoundsException

时间:2016-11-26 23:19:31

标签: java

我正在尝试比较两个字符,但在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); 
            ...
        }
    }
}

2 个答案:

答案 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获取0phrasetwo.length - 1的值。然后,它会引用iphrasetwo中位置guesstwo处的字符。如果phrasetwo长于guesstwo,那么发生错误的语句将尝试引用字符串末尾的字符。因此错误。