Tuesday, September 7, 2010

HW 1 Solution

Here is my solution to the HW1 problem:
/** @author Jose M Vidal  
 * Rotate lowercase only strings by an arbitrary amount, without using if-then statements.
 * */

import java.util.Scanner;

public class Rot13 {

 /**
  * @param args are ignored
  */
 public static void main(String[] args) {
  Scanner keyboard = new Scanner(System.in);
  System.out.print("What offset do you want?");
  int offset = keyboard.nextInt();
  System.out.print("Enter word to translate:");
  String inputWord = keyboard.next();
//  for (char c : inputWord.toCharArray()) { //a classier way to do the same
  for (int i = 0; i < inputWord.length(); i++) {
   //Don't replace ('z' - 'a' + 1) with its value, the compiler will do that.
   char c = inputWord.charAt(i);
   System.out.print((char)('a' + (c - 'a' + offset) % ('z' - 'a' + 1)));
  }
 }
}

No comments: