谢谢各位,这段代码正负数KEY和运算方式我都明白,唯一不明白的是'A'的作用。
问题一:下面有两段代码,其中代码A运行时是错的,但我不明白错误在何处。
问题二:代码B是正确的,但我不明白为什么需要先减去'A',然后求余数之后再加上'A'.这个'A'是什么作用?为什么删除之后就运行出错呢(问题一)?
Code A (ch + key) % 26 )
Code B ('A' + ((ch -'A' + key) % 26))
public void run() {
setFont("Arial-PLAIN-24");
String line = readLine ("Enter line: ");
int key = readInt ("Enter key: ");
String siphertext = encryptCaesar(line , key);
println("The result is: " + siphertext);
String newplain = encryptCaesar(siphertext , -key);
println("newplain:" + newplain);
}
private String encryptCaesar(String str , int key){
if(key < 0){
key = 26 - ( -key % 26 );
}
String result = "";
for(int i = 0; i < str.length(); i++){
char ch = str.charAt(i);
result += encryptChar(ch,key);
}
return result;
}
private char encryptChar(char ch, int key){
if(Character.isUpperCase(ch)){
return ( (char) ('A' + ((ch -'A' + key) % 26)) );
}
return ch;
}