Rot13 (Java)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Forth | Haskell | Java | Scheme | Sed

Here, we present a Java program that performs Rot13 encoding and/or decoding for text passed on the command line or via a filter.

The heart of this cipher is a simple character substitution that moves the letters greater than or equal to 'n' 13 places towards the front of the alphabet and letters less than or equal to 'm' 13 places towards the back. This is done separately for the lower case and upper case letters. Punctuation and non-English characters are left unchanged.

For example, if the plain text was:

Now is the Winter of our Discontent,
Made glorious Summer by this Son of Yorke:

The encoded string would be:

Abj vf gur Jvagre bs bhe Qvfpbagrag,
Znqr tybevbhf Fhzzre ol guvf Fba bs Lbexr:

If the Rot13 algorithm is reapplied to the encoded string, the original plain text is returned.

We also take the opportunity to introduce the reader to the JUnit test framework and the Apache Ant build tool, both of which are a standard part of the professional Java development toolbox.

Contents

The Algorithm

In the following, c is the character currently being encoded.

<<encode c>>=
if      (c >= 'a' && c <= 'm') c += 13;
else if (c >= 'n' && c <= 'z') c -= 13;
else if (c >= 'A' && c <= 'M') c += 13;
else if (c >= 'N' && c <= 'Z') c -= 13;

A function to use this method would simply take a string, extract the characters, encode them using the character encoding scheme, and rebuild a string from the encoded text, as follows:

<<encoder>>=
/**
 * Encode plain text using the Rot13 algorithm.
 * @param plainText the plain text message.
 * @returns the plain text message encoded using the Rot13 algorithm.
 */
public static String encode(String plainText) {
  // deal with the case that method is called with null argument
  if (plainText == null) return plainText;
  // encode plainText
  String encodedMessage = "";
  for (int i = 0; i < plainText.length(); i++) {
    char c = plainText.charAt(i);
    encode c
    encodedMessage += c;
  }
  return encodedMessage;
}

Testing the Algorithm

For the test we shall use part of the opening soliloquy quote from Act I Scene I of William Shakespeare's Richard III.

<<declare test strings>>=
private String plainText;
<<define test strings>>=
plainText = "Now is the Winter of our Discontent,\n" +
            "Made glorious Summer by this Son of Yorke:\n" +
            "And all the clouds that lowr'd vpon our house\n" +
            "In the deepe bosome of the Ocean buried.\n" +
            "Now are our browes bound with Victorious Wreathes,\n" +
            "Our bruised armes hung vp for Monuments;\n" +
            "Our sterne Alarums chang'd to merry Meetings;\n" +
            "Our dreadfull Marches, to delightfull Measures.\n" +
            "Grim-visag'd Warre, hath smooth'd his wrinkled Front:\n" +
            "And now, in stead of mounting Barbed Steeds,\n"</fo