这是从原问题中扩展出来的,因为还有更多不明白的地方,而且不容易在评论里讨论,所以重新开一个题目。
问题背景:
可以运行的原代码 CODE[A] return ( (char) ('A' + ((ch -'A' + key) % 26)) );
运行位置在 private char encryptChar(char ch, int key){}
中。
无法输出的代码 CODE [B] return ( (char) ((ch+ key) % 26) );
按@xiaoyan_12解释:
添加'A'是确保"encryptChar" 方法的结果在 ASCII 范围64 to 90(A (CAPITAL) to Z (CAPITAL))是一个有效的字符。在你的代码中减去'A'也可以忽略,('A' + ((ch + key) % 26))也会运行。
问题一: 它的运算过程是怎样的呢,只是求余数的时候少减去了'A',为什么加密结果错了15位?
CODE [C]: return ( (char) ('A'+((ch+ key) % 26)) );
运行结果是
Enter line: ABC
Enter key: 1
The result is: OPQ
newplain:ABC
问题二: 既然添加'A'是确保"encryptChar" 方法的结果是一个有效的字符。所以我使用了CODE[D] ( (char) ('A'+(((ch+ key) % 26) - 'A')));
以及转换了括号位置( (char) ('A'+(((ch+ key) % 26) - 'A')));
我也试过( (char) ('B'+(((ch+ key) % 26) - 'A')));
但都无法输出有效字符。
CODE[D] 只比 CODE[C]多了- 'A'
为什么也不能输出字符了呢?
运行结果是
Enter line: ABC
Enter key: 1
The result is:
newplain:
自学JAVA,提问不清晰请见谅。
代码:
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;
}`enter code here`