// Tyler Rigsby, CSE 142 // Allows encoding and decoding of secret messages via a Caesar Cipher import java.util.*; public class CaesarCipher { public static void main(String[] args) { System.out.println("Welcome to the CSE 142 Caesar Cipher program!"); Scanner console = new Scanner(System.in); System.out.println("Enter your message to encode or decode: "); String message = console.nextLine(); message = message.toLowerCase(); System.out.print("Please enter the key: "); int key = console.nextInt(); System.out.print("Do you want to (E)ncode or (D)ecode? "); String answer = console.next().toLowerCase(); if (answer.startsWith("e")) { String encoded = shift(message, key); System.out.println("The encoded message is: " + encoded); } else { String decoded = shift(message, -key); System.out.println("The decoded message is: " + decoded); } } // Returns a String with all the letters of message in the a-z range shifted // by the value of key. e.g. "foo" with a key of 2 becomes "hqq" public static String shift(String message, int key) { String result = ""; for (int i = 0; i < message.length(); i++) { char letter = message.charAt(i); // only want to apply shift if the character is between a-z if (letter >= 'a' && letter <= 'z') { letter = (char) (letter + key); // or, letter += key // if that shifts it outside the a-z range, subtract or add 26 to // loop back around if (letter > 'z') { letter -= 26; } else if (letter < 'a') { letter += 26; } } result = result + letter; // or, result += letter } return result; } }