下面的代码以 Caesar 的方式加密了一个单词或句子。您输入移位值,程序会根据移位(键)值获取单词/句子的每个字母并在字母表中“移动”。但这不是问题。 我在互联网上找到了代码,但我无法解释其中的某些行。 我知道它是如何工作的,但我需要一些关于它的一些线路的具体答案。 这是代码:
import acm.program.*;
public class CaesarCipher extends ConsoleProgram {
public void run() {
println("This program implements a Caesar cipher.");
int key = readInt("Character positions to shift: ");
String plaintext = readLine("Enter a message: ");
String ciphertext = encodeCaesarCipher(plaintext, key);
println("Encoded message: " + ciphertext);
}
private String encodeCaesarCipher(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);
if (Character.isLetter(ch)) {
if (Character.isUpperCase(ch)) {
ch = (char) ('A' + (ch - 'A' + key) % 26);
}
else {
ch = (char) ('a' + (ch - 'a' + key) % 26);
}
}
result += ch;
}
return result;
}
}
这些线条到底是什么意思,它们是如何做的?
ch = (char) ('A' + (ch - 'A' + key) % 26);
和
ch = (char) ('a' + (ch - 'a' + key) % 26);
最佳答案
除了一行适用于大写字母而另一行适用于小写字母之外,这两行的行为相同。我将在这里解释大写操作。请记住,在下面的第 6 步之前,这些 char
值被视为 int
。
ch = (char) ('A' + (ch - 'A' + key) % 26);
ch - 'A'
给出初始字符相对于大写字母 A 的int
偏移量。ch - 'A' + key
将偏移量增加key
,创建加密字符相对于大写字母 A 的偏移量。(ch - 'A' + key) % 26
:这里的取模保证了加密字符的数值为0-25(对于字母表中的26个字母),防止alphabet “溢出。”该表达式的值现在是加密字符相对于大写字母 A 的标准化偏移量。'A' + (ch - 'A' + key) % 26
将加密字符从大写字母 A 到大写字母 A 本身的偏移量相加,得到加密字符的int
值。(char) ('A' + (ch - 'A' + key) % 26)
将int
转换为char
类型,导致加密字符为char
。
此代码将字母表的开头(大写字母 A)视为“起点”,从这里开始测量每个字母的偏移量。偏移量是字符从“A”开始的字母数。
示例:使用 key 6 对“E”进行加密:
- 找出“E”和大写字母 A 之间的字母数。 A 的 ASCII 码是 65,E 的代码是 69。要找到 E 与 A 的偏移量,减去
69 - 65 = 4
。 - 添加偏移量和 key :
4 + 6 = 10
。这是加密字符 A 中的字母数。 10 % 26 = 10
(没有效果,因为小首字母 + 小键)'A' + 10 = 65 + 10 = 75
得到加密字符的 ASCII 码 75 ('K')- 将 75 转换为
char
可以将其视为字符,而不是int
。
关于java - 带有 java acm 的凯撒密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20793472/