0

java.lang.ArrayIndexOutOfBoundsException当我尝试运行某些字母(e)并且我不知道如何解决它时,我的代码中的线程“main”中出现错误异常:26。

该数组包含 26 个字符(字母表中的每个字母)。任何人都可以在代码中看到问题吗?

//Breaking up the letters from the input and placing them in an array
char[] plaintext = input.toCharArray();
//For loops that will match length of input against alphabet and move the letter 14 spaces
for(int i = 0;i<plaintext.length;i++) {
    for(int j = 0 ; j<25;j++) {
        if(j<=12 && plaintext[i]==alphabet[j]) {
            plaintext[i] = alphabet[j+14];
            break;
        }
        //Else if the input letter is near the end of the alphabet then reset back to the start of the alphabet
        else if(plaintext[i] == alphabet[j]) {
            plaintext[i] = alphabet [j-26];
        }
    }
}
4

4 回答 4

4
if(j<=12 && plaintext[i]==alphabet[j]) {
     plaintext[i] = alphabet[j+14];
     break;
}

此代码将访问alphabet[26]ifj == 12plaintext[i]==alphabet[j]. 您的数组具有索引0-25。Java 数组具有从零开始的索引。

于 2013-05-06T12:33:56.933 回答
3

如果它包含 26 个字符(如您所说),那么最后一个索引是 25 而不是 26。这会导致问题。

你有j<=12所以当j是 12 然后你有索引 26 ( j+14) 并且它不在数组中。

于 2013-05-06T12:32:22.677 回答
3

你有边缘情况,j == 12你取消引用alphabet[j+14]== alphabet[26]

于 2013-05-06T12:33:41.470 回答
3

什么时候j是 12,你会得到26。由于 Java 中的数组是从零开始的数组,因此您的数组索引是从 0 到 25,因此 26 是 outOfBounds。

  if(j<=12 && plaintext[i]==alphabet[j]){
     //Check if j+14 doesn't exceed 25

另一件事,你的 for 循环应该是for(int j = 0 ; j<26;j++){(别担心,25 是最后一个索引)。

顺便说一句,您得到的异常信息非常丰富。在这种情况下,使用调试器会有很大帮助。

于 2013-05-06T12:33:50.077 回答