java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 26

标签 java arrays encryption

当我尝试运行某些字母(e)时,我在代码中收到错误 Exception in thread "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 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];
        }
    }
}

最佳答案

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

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

关于java - 线程中的异常 "main"java.lang.ArrayIndexOutOfBoundsException : 26,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16398830/

相关文章:

java - 如何在不使用模式的情况下在 DateTimeFormatterBuilder 中指定区域偏移量?

javascript - 如何在 vue.js 中不使用循环方法将类型数组对象更改为格式化对象?

c - 从文件中读入C中的数组

php - 对多个字段使用相同的盐

c# - System.Security.Cryptography.RSA.Encrypt 方法中是否假定 MGF1 填充与 RSAEncryptionPadding.OaepSHA256?

java - 无法使用 Stax 中的 XMLEventReader 检查 XML 中的 CDATA

Java:为什么这些变量不初始化?

java - java中的线程同步/生产者-消费者。重复打印数字 1-10 然后 10-1

php - 将 MySQL 结果存储在关联数组中

java - PBE : Verify password before attempting to decrypt