为什么我的 findPosition 方法出现 "java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5" 错误?

Why am I getting a "java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5" error for my findPosition method?

第一个 Class 给我错误。我要用字母 A-Z 创建一个数组,然后让用户输入它所需要的键,并将键数组中每个字符的位置与用户输入的字符串

的位置进行比较
import java.util.*;
    public class Encrypt{
        private Square plain1;
        private Square plain2;
        private Square Encrypt1;
        private Square Encrypt2;

    public Encryption(String key1, String key2) {
        plain1 = new Square();
        plain2 = new Square();
        Encrypt1= new Square(key1);
        Encrypt2= new Square(key2);
    } 


    public String encrypt(String msg) {
        String EmpS = "";
        String STR = "";

        for(int i = 0; i < message.length(); i+=2){
            char iMsg = message.charAt(i);
            char iMsg2 = message.charAt(i+1);
            int[] posRay = plain1.findPosition(iMsg);
            int[] posRay2 = plain2.findPosition(iMsg2);
            String answer = "" + Encrypt1.getChar(posRay[0], posRay2[1]);
            String Combined = "" + answer;
            String answer2 = "" + Encrypt2.getChar(posRay2[0], posRay[1]);
            String Combined2 = "" + answer2;

            String BothCom = Combined + Combined2;
            STR = STR.concat(BothCom);

        return STR;
        }
        return STR;
    } 

负责数组的第2个class

public class Square {
    private char[][] matrix;
public Square() {
        arr= new char[5][5];
        int ascii= 65;
        for (int i = 0; i < 5; i++){
            for(int j = 0; j < 5; j++){
                arr[i][j] = (char) ascii;
                ascii++;
                }
            }
        }
}
public int[] findPosition(char Chart) {
        int[] position= new int[2];
        position[0] = -1;
        popositions[1] = -1;
        for (int i = 0; i < 5; i++){
            for (int j = 0; i < 5; j++){
                if(matrix[i][j] == Chart){
                posistion[0] = i;
                position[1] = j;
                return position;
                }
            }
        }

我将此视为错误(其他一切正常),并且我已尝试更改数组的大小并调整 for 循环,但我仍然不确定为什么我会收到错误问题?:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at Square.findPosition(Square.java:91)
    at Encrypt.encrypt(Encrypt.java:45)
    at IO.printResults(IO.java:101)
    at Lab.main(Lab.java:26)

for (int j = 0; i < 5; j++){

应该是 j < 5i < 5 条件为真并且无论循环多少次都保持为真,因此,您最终得到 j = 5 并且该索引不存在。

注意:我只是在猜测。 很明显 不是您实际编写的代码,因为其中有大量错别字,如果不修复所有错别字 将无法编译.

下次粘贴导致实际错误的实际代码,而不是...此处发生的任何事情。你是手写的吗?哎呀

字段矩阵未初始化。我的意思是 class 方块中的矩阵在哪里? 另一件事:构造函数中的 arr 是从哪里来的? 现在你会知道了。