| Fifth Assignment: Caesar Cipher CIT 591, David Matuszek, Fall 2001 |
The purpose of this assignment is to give you some practice using characters, Strings, and StringBuffers. A second purpose it to give you additional practice in using the Java API to find the methods you need. I will suggest some methods you might need at the bottom of this page.
This assignment, like the last one, makes very little use of classes and objects,
although it does use some of Java's predefined classes (Character,
String and StringBuffer, in particular). This should
be a relatively easy assignment.
The idea of a Caesar cipher is this: you encode a message by shifting each letter some number of places. Thus, if the shift is 2, then A becomes C, B becomes D, and so on. Like this:

Surprisingly, you can do this by simply doing arithmetic with
characters, but you do need to reassure Java that the result is a character.
If, for example, char letter contains the value 'A',
then 'A' + 2 gives the integer result 67,
which you can turn back into a character by saying (char)(letter + 2),
giving the value 'C'. Unfortunately, (char)('Z' + 2)
does not give you the letter 'B' (you can see why from the
picture above), but if you realize you went past 'Z', you can subtract
26 (so the result is 'Z' + 2 - 26, or 'Z' - 24),
and this will give you 'B'.
This also means that if you encode a message with a shift of
n, you can decode it with another shift of 26 - n.
Here's the assignment:
Strings. Here is the source code
for a LineReader class you can use to do the
reading.StringBuffer (not a String).
Discard all the punctuation marks, digits, blanks, and anything else from
the input string.For example, given a shift of 1, the program will turn this:
Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances.
into this:
DPOHS FTTTI BMMNB LFOPM BXSFT QFDUJ OHBOF TUBCM JTINF OUPGS FMJHJ POPSQ SPIJC JUJOH UIFGS FFFYF SDJTF UIFSF PGPSB CSJEH JOHUI FGSFF EPNPG TQFFD IPSPG UIFQS FTTPS UIFSJ HIUPG UIFQF PQMFQ FBDFB CMZUP BTTFN CMFBO EUPQF UJUJP OUIFH PWFSO NFOUG PSBSF ESFTT PGHSJ FWBOD FT
To use the LineReader class:
LineReader reader = new LineReader("Encrypt what file?");
line = reader.readLine();reader.readLine() returns null (you can test with line == null),
you didn't get a line, and you are done reading. Close the file with: reader.close();Useful methods you should look at:
Character.isLetter(char)Character.toUpperCase(char)String.charAt(int)String.length()StringBuffer.append(char)StringBuffer.length()