Learning Java – Rot13

I’m planning to do a masters degree in computing in the next year or two. Most of the courses I’ve been looking at are built around Java, so I thought it would be a good idea to learn a bit now when I can relax and take my time. So I’ve been working through the tutorial over the last few days. I’m done with the basics and will shortly be moving on to those essential java classes. So I’m at the point where I can write some little programs to test that I actually do know what’s going on. This fancy book learning is all very well, but I like to get my hands dirty with whatever I’m trying to understand, so I’ll be trying out my knowledge as I go along.

This first program is pretty damn simple. But it’s the first program I’ve ever written in Java, so I’m kind of proud of it. It’s an implementation of the rot13 cipher.:

public class Rot13 {
    static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
    private static char rotateChar(char c) {
        if (Character.isLetter(c)) {
            int idx = ALPHABET.indexOf(Character.toLowerCase(c));
            idx += 13;
            if (idx >= 26) {
                idx -= 26;
            }
            char rotatedChar = ALPHABET.charAt(idx);
            if (Character.isUpperCase(c)) {
                return Character.toUpperCase(rotatedChar);
            }
            else {
                return rotatedChar;
            }
        }
        else {
            return c;
        }
    }
 
    public static String rotate(String source) {
        char[] resultArray = new char[source.length()];
        for (int i = 0; i < source.length(); i++) {
            resultArray[i] = rotateChar(source.charAt(i));
        }
        return new String(resultArray);
    }
 
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            System.out.println(rotate(args[i]));
        }
    }
}

This stuff is easier in Python, where I’d write something like:

import string, sys
transtable = string.maketrans(string.ascii_letters,
                 string.ascii_lowercase[13:] +
                 string.ascii_lowercase[:13] +
                 string.ascii_uppercase[13:] +
                 string.ascii_uppercase[:13])
for arg in sys.argv[1:]:
    print string.translate(arg, transtable)

Actually, I could write it on one line using less than 200 characters. Not that this is a good idea, but...

import string as s;import sys;a=s.ascii_lowercase;
b=s.ascii_uppercase;[sys.stdout.write(s.translate(
arg,s.maketrans(s.ascii_letters,a[13:]+a[:13]+
b[13:]+b[:13]))+"\n") for arg in sys.argv[1:]]

So yeah, Java does seems a bit verbose at the moment.


Leave a Reply