事实上,如果使用代码[A],运行会失败。我不明白为什么。我也不明白先 -'A' 然后 +'A'。为什么 [A] 失败了?[乙]好吗?
Code [A] (char) (ch + key) % 26 )
Code [B] (char) ('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;
}
/**Why can't use ( (ch + key) % 26 )*/
private char encryptChar(char ch, int key){
if(Character.isUpperCase(ch)){
return ( (char) ('A' + ((ch -'A' + key) % 26)) );
}
return ch;
}