为何我的Java加密程序中findPosition方法会抛出java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5错误?
解决Java数组越界异常(ArrayIndexOutOfBoundsException)及代码中的其他问题
你遇到的ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5异常,核心原因是Square类的findPosition方法里内层循环条件写错了,咱们一步步拆解所有问题:
1. 直接触发数组越界的根源:Square类findPosition方法的循环错误
在findPosition方法的内层循环里,你把判断条件写成了i < 5而非j < 5!这会导致j不受控制地递增,直到超过5x5数组的最大索引4(数组索引范围是0-4),当j=5时就抛出了数组越界异常。
除此之外,这个方法里还有几个拼写错误,同样会导致逻辑失效:
popositions[1] = -1;→ 应该是position[1] = -1;posistion[0] = i;→ 应该是position[0] = i;- 还缺少了未找到字符时的返回语句
修正后的findPosition方法:
public int[] findPosition(char Chart) { int[] position= new int[2]; position[0] = -1; position[1] = -1; for (int i = 0; i < 5; i++){ for (int j = 0; j < 5; j++){ // 这里把i改成j if(matrix[i][j] == Chart){ position[0] = i; position[1] = j; return position; } } } return position; // 确保未找到字符时也有返回值 }
2. Square类构造方法的变量名不匹配
Square类的成员变量是matrix,但构造方法里你错误地使用了arr,这会导致matrix始终为null,后续所有数组操作都会报错:
// 修正后的构造方法 public Square() { matrix= new char[5][5]; // 将arr改为matrix int ascii= 65; for (int i = 0; i < 5; i++){ for(int j = 0; j < 5; j++){ matrix[i][j] = (char) ascii; ascii++; } } }
3. Encrypt类的几个关键错误
3.1 构造方法名与类名不匹配
你的类名是Encrypt,但构造方法写成了Encryption,这会导致无法正确实例化Encrypt对象:
// 修正后的构造方法 public Encrypt(String key1, String key2) { plain1 = new Square(); plain2 = new Square(); Encrypt1= new Square(key1); Encrypt2= new Square(key2); }
3.2 encrypt方法的变量名不匹配
方法参数是msg,但你在循环里用了未定义的message,这会直接导致编译错误:
// 把所有message替换为msg for(int i = 0; i < msg.length(); i+=2){ char iMsg = msg.charAt(i); char iMsg2 = msg.charAt(i+1); // ...后续逻辑 }
3.3 循环内部提前return
你把return STR;放在了循环内部,这样第一次循环执行完就直接返回结果,完全无法处理后续字符,需要把这个return移到循环外部。
修正后的encrypt方法:
public String encrypt(String msg) { String STR = ""; for(int i = 0; i < msg.length(); i+=2){ char iMsg = msg.charAt(i); char iMsg2 = msg.charAt(i+1); int[] posRay = plain1.findPosition(iMsg); int[] posRay2 = plain2.findPosition(iMsg2); String answer = "" + Encrypt1.getChar(posRay[0], posRay2[1]); String answer2 = "" + Encrypt2.getChar(posRay2[0], posRay[1]); String BothCom = answer + answer2; STR = STR.concat(BothCom); } return STR; // 移到循环外部 }
内容的提问来源于stack exchange,提问作者Chibuike S. Eze
相关产品推荐
相关产品推荐

