Prev << >> On to the next chapter: Fifteen Puzzle.
When Julius Caesar had to send military secrets to his generals, he used this cipher:
In the Caesar cipher, every letter is replaced by the letter that comes 3 slots after it in the alphabet. For example, the letter "a" is replaced by the letter "d". Letters at the end of the alphabet are wrapped around so that "z" goes to "c". Of course you can make a similar cipher by shifting by a different number of slots - the ROT13 cipher shifts by 13, and it has the property that you can decode a message by encrypting it twice.
This is another event-based program, so it is organized with the same general four phases as any event-based program. An overview:
This program does both input validation, where it rejects input that doesn't look sensible, and input normalization, where it changes the input to make it easier to work with.
Let us take a look at the encryption procedure. The general idea is to convert each letter to a number, add 3 (or whatever key), and then convert the number back to a letter again. To do this, we use two string methods:
string.indexOf(search) | indexOf returns
the first location of of the search string within the string. For example, 'hello there'.indexOf('the') returns 6. If the search string isn't found, returns -1. |
string.charAt(index) | charAt returns
the character at the given index within the string. For example, 'hello there'.charAt(6) returns 't'. |
To encrypt the letter 'e' as 'h', we:
Characters that are not found are passed unencrypted.