The code below encrypts a word or sentence in the way Caesar did. You put the shift value and the program takes each letter of the word/sentence and "moves" in the alphabet acoording to the shift (key) value. But this is not the problem. I found the code on the internet and i cannot explain some of it's lines. I know how it works but i need some specific answer about some of it's lines. Here is the code:
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;
}
}
What exactly do those lines mean, and how do they do what they do?
ch = (char) ('A' + (ch - 'A' + key) % 26);
and
ch = (char) ('a' + (ch - 'a' + key) % 26);
Those two lines behave identically, except for the fact that one applies to uppercase, and one to lowercase. I'll explain the uppercase operations here. Keep in mind that these
char
values are treated asint
s until step 6 below.ch - 'A'
gives the initial character'sint
offset from capital-A.ch - 'A' + key
increases the offset bykey
, creating the ciphered character's offset from capital-A.(ch - 'A' + key) % 26
: the modulo here ensures that the numeric value of the ciphered character is 0-25 (for the 26 letters in the alphabet), preventing alphabet "overflow." The value of that expression is now the normalized offset of the ciphered character from capital-A.'A' + (ch - 'A' + key) % 26
adds the ciphered character's offset from capital-A to capital-A itself, resulting in the ciphered character'sint
value.(char) ('A' + (ch - 'A' + key) % 26)
casts thatint
tochar
type, resulting in the ciphered character as achar
.This code treats the beginning of the alphabet (capital-A) as the "starting point," from which each letter's offset is measured. The offset is the character's number of letters from 'A'.
Example: To cipher "E" with a key of 6:
69 - 65 = 4
.4 + 6 = 10
. This is the number of letters from A the ciphered character will be.10 % 26 = 10
(no effect because of the small starting letter + small key)'A' + 10 = 65 + 10 = 75
results in the ASCII code of the ciphered character, 75 ('K')char
allows it to be treated as a character, rather than anint
.