我是Java新手,我尝试编写Caesar密码包括大写和小写字符。我不知道为什么编码错误。有人帮助我,我很感激它感谢一百万。 这是我到目前为止的代码。
public class CaesarCipher{
char[] encoder = new char[52];
char[] decoder = new char[52];
public CaesarCipher(int rotation)
{
for(int k=0 ; k < 26 ; k++)
{
encoder[k] = (char) ('A' + (k + rotation) % 26);
decoder[k] = (char) ('A' + (k - rotation + 26) % 26);
}
for(int j = 26 ; j < 52 ; j++ )
{
encoder[j] = (char)('a' + (j + rotation) % 26);
decoder[j] = (char)('a' + (j - rotation) % 26);
}
}
public String encrypt(String message) {
char[] msg = message.toCharArray();
for(int i = 0 ; i < msg.length ; i++){
if(Character.isUpperCase(msg[i])){
msg[i] = encoder[msg[i] - 'A'];
}
else{
int n = msg[i] - 'a' ;
msg[i] = encoder[26 + n];
}
}
return new String(msg);
}
public String decrypt(String secret) {
char[] msg = secret.toCharArray();
for(int i = 0 ; i < msg.length ; i++){
if(Character.isUpperCase(msg[i])){
msg[i] = decoder[msg[i] - 'A'];
}
else{
int n = msg[i] - 'a';
msg[i] = decoder[26 + n];
}
}
return new String(msg);
}
public static void main(String[] args) {
CaesarCipher cipher = new CaesarCipher(3);
String message = "There Is an APPle";
String coded = cipher.encrypt(message);
System.out.println("Secret: " + coded);
String answer = cipher.decrypt(coded);
System.out.println("Message: " + answer);
}
}
答案 0 :(得分:2)
运行我的代码
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -39
at t1.CaesarCipher.encrypt(CaesarCipher.java:30)
at t1.CaesarCipher.main(CaesarCipher.java:54)
此时正在执行的代码是
int n = msg[i] - 'a' ;
msg[i] = encoder[26 + n];
我是5,但你的输入数据是&#34;有一个APPle&#34;
索引5处的字符是一个空格,但您正在尝试减去&#39; a&#39;从中获得负面指数。