/********************************************************************** * Matt Kretchmar * April 1, 2006 * Cryptogram.java * This program prompts the user to enter a famous quote or phrase. * It then uses a permuted alphabet to substitute letters in the * phrase to create a scrambled version of the quote. Basically, * this program creates a cryptogram puzzle. ***********************************************************************/ import java.util.Scanner; import java.util.Random; class Cryptogram { public static void main ( String args[] ) { // prompt the user for a famous quote or phrase String quote = getQuote(); // create an array with 'A'...'Z' letters char key[] = getAlphabet(); // print the quote print(quote); // print the alphabet print(key); // randomly re-order the alphabet permute(key); // print the shuffled alphabet print(key); // scramble the quote by using the shuffled alphabet (key) String puzzle = scramble(key,quote); // print the scrambled quote print(puzzle); } /** * A method to read the user's quote, convert all letters * to uppercase and return the quote. */ public static String getQuote ( ) { System.out.println("Enter a famous quote or phrase: "); Scanner keyboard = new Scanner(System.in); return (keyboard.nextLine()).toUpperCase(); } /** * A method to create and return an array of 26 characters * containing the upper case alphabet. */ public static char[] getAlphabet() { char a[] = new char[26]; for ( int i = 0; i < 26; i++ ) a[i] = (char)('A' + i); return a; } /** * A method to print an array of characters. */ public static void print ( char a[] ) { System.out.println(a); } /** * A method to print a string. */ public static void print ( String s ) { System.out.println(s); } /** * This method permutes the charaters in the array * in a new random order. Each character has equal * probability of ending up in each location. */ public static void permute ( char a[] ) { Random generator = new Random(); for ( int i = 0; i < a.length-1; i++ ) { int position = generator.nextInt(a.length-i)+i; char temp = a[i]; a[i] = a[position]; a[position] = temp; } } /** * This method creates a new "scrambled" version of the * phrase input string. It uses the permuted alphabet in * the key array to make the letter substitutions. */ public static String scramble ( char key[], String phrase ) { String puzzle = ""; for ( int i = 0; i < phrase.length(); i++ ) { char c = phrase.charAt(i); if ( c >= 'A' && c <= 'Z' ) { int position = phrase.charAt(i) - 'A'; puzzle = puzzle + key[position]; } else { puzzle = puzzle + c; } } return puzzle; } }