问题一:下面是两个代码微调器。代码A运行错误。但我不知道什么是错的。有关字符串加密调度的错误:(char)(ch + key)%26
问题二:代码B是对的,但我不明白为什么需要删除'A'。然后在fmod后添加'A'。 'A'有什么影响?为什么删除后有错误?
代码A(CH +键)%26)
代码B( 'A' +((CH -'A” +键)%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;
}
你是什么意思,该代码“跑错了”?请发布一个完整的示例,重现问题并准确描述问题所在。 – 2013-03-07 02:18:25