“线程中的异常”;“主要”;java.lang.ArrayIndexOutOfBoundsException:26
当我试图运行某些字母(e)时,我的代码中出现了线程“main”“线程中的异常”;“主要”;java.lang.ArrayIndexOutOfBoundsException:26,java,arrays,encryption,Java,Arrays,Encryption,当我试图运行某些字母(e)时,我的代码中出现了线程“main”java.lang.ArrayIndexOutOfBoundsException:26中的错误异常,我不知道如何解决它 数组包含26个字符(字母表中的每个字母)。有人能看到代码中的问题吗 //Breaking up the letters from the input and placing them in an array char[] plaintext = input.toCharArray(); //For loops tha
java.lang.ArrayIndexOutOfBoundsException
: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];
}
}
}
//从输入中拆分字母并将其放入数组中
char[]明文=input.toCharArray();
//用于将输入长度与字母表匹配并将字母移动14个空格的循环
对于(inti=0;i如果它包含26个字符(如您所说),那么最后一个索引是25而不是26。这会导致问题
你有j当j
为12时,你有一个边缘情况,其中j==12
,你去引用alphabet[j+14]
=alphabet[26]当j
为12时,你会得到26。因为Java中的数组是零基数组,你的数组索引从0到25,所以26是边界外的
if(j<=12 && plaintext[i]==alphabet[j]){
//Check if j+14 doesn't exceed 25
if(jif(jArrays从0开始。如果它包含26个入口,它将在0-25范围内。谢谢,加密正在工作,但现在解密在第14个字母后给出了错误的输出。我需要更改什么?我更新了上面的decrytion代码。@d99这是一个完全不同的问题。请接受这里的任何答案,它们或多或少都是e。)同样有帮助。然后试着自己解决它。之后,如果需要,再问另一个问题。对不起,我自己尝试过,但没有真正找到问题所在,我认为这是相关的。我已经接受了你的答案,谢谢。不用担心,但我建议你仔细考虑你的解决方案,并可能尝试不同的方法。你会学到一个l这样做更多,并最终成为更好的编码员。:)
if(j<=12 && plaintext[i]==alphabet[j]) {
plaintext[i] = alphabet[j+14];
break;
}