gpt4 book ai didi

java - 凯撒加密。数组在索引 73(共 73 个)中超出范围

转载 作者:行者123 更新时间:2023-12-01 18:45:05 26 4
gpt4 key购买 nike

我正在为数学演示编写凯撒加密代码。今天,我一直在为我的演讲编写代码。早上这个代码就开始工作了。但现在在学校,我遇到了一个异常(exception),我认为 for 超出了我的符号表的长度。

异常(exception):

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index 73 out of bounds for length 73 at caesarForm.decrypt(caesarForm.java:81)

第 81 行是 decrypt() 中的第三个 for

如果有人可以查看我的代码,我会很高兴,因为以我 3 个月的编码经验,我无法理解发生了什么。

//Alphanumeric table
final static char[] symbs = new char[] {'.',',','1','2','3','4','5','6','7','8','9','0','/','z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a',' '
,'ß','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','ä','ö','ü','Ü','Ö','Ä'};
final static int charlength = 73;

//var global key
int key = 0;

//en- and decryption vars
char[] letters = new char[255];
char[] storg = new char[255];
char[] sterg = new char[255];
StringBuilder str = new StringBuilder();
int cnt = 0;
int cnt2 = 0;
int c = 0;
String bakToStr;

textField1.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
char iNumber = e.getKeyChar();
if (!(Character.isDigit(iNumber))
|| iNumber == KeyEvent.VK_BACK_SPACE
|| iNumber == KeyEvent.VK_DELETE) {
e.consume();
JOptionPane.showMessageDialog(contentPane, "Nur Zahlen werden als schlüssel akzeptiert", "Achtung!", JOptionPane.INFORMATION_MESSAGE);
}
}
});

public String encrypt(String Text) {
letters = new char[255];
storg = new char[255];
sterg = new char[255];
str = new StringBuilder();
cnt = 0;
cnt2 = 1;
c = 0;
bakToStr = "";
for (int i = 0; i <Text.length(); i++) {
letters[i] = Text.charAt(i);
}
for (; cnt < Text.length(); cnt++) {
for (;letters[cnt] != symbs[cnt2];cnt2++) {
}
c = (cnt2 + key) %charlength;
storg[cnt] = symbs[c];
cnt2 = 0;
}
str.append(storg);
bakToStr = String.valueOf(str);
return bakToStr;
}

public String decrypt(String Text) {
letters = new char[255];
storg = new char[255];
sterg = new char[255];
str = new StringBuilder();
cnt = 0;
cnt2 = 1;
c = 0;
bakToStr = "";
for (int i = 0; i <Text.length(); i++) {
letters[i] = Text.charAt(i);
}
for (; cnt < Text.length(); cnt++) {
for (;letters[cnt] != symbs[cnt2];cnt2++) {
}
c = (cnt2 - key) %charlength;
while (c <= 0) {
c += charlength;
}
storg[cnt] = symbs[c];
cnt2 = 0;
}
str.append(storg);
bakToStr = String.valueOf(str);
return bakToStr;
}

最佳答案

请考虑这一行:

while (c <= 0) {
c += charlength;
}

如果 c==0 会发生什么?我认为它会跳到73这是 charlength 。所以,这里更好的方法是使条件 while (c < 0)而不是while (c <= 0) .

但是,我认为主要问题在于第三个 for 循环:

for (;letters[cnt] != symbs[cnt2];cnt2++)

因为cnt2初始化为值 1 (不是 0 )并递增。如果不满足条件,则 cnt2 将始终递增,因此变为 73并抛出 indexOutOfBound异常。

希望对你有帮助:)

关于java - 凯撒加密。数组在索引 73(共 73 个)中超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59854602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com