Caesar Shift

/** * Encrypts a word (only letters) using a caesar shift. * * @Laura * @1.0 */ import java.util.*; import java.lang.Integer.*; public class CaesarShift { public static void main(String[] args) { int shift = 0; //initializes variables int index = 0; int modIndex = 0; String encrypted = ""; String temp = ""; String shiftStr = ""; String alphabet = "abcdefghijklmnopqrstuvwxyz"; //storing alphabet System.out.print("Enter a word (only letters): "); //prompts for word Scanner s = new Scanner(System.in); String word = s.nextLine(); while (checkIfStringIsNumber(word)) { //checks if word entered was a number System.out.print("That is not a valid answer. Enter a word (only letters): "); //re-prompts for word word = s.nextLine(); } System.out.print("Enter how many letters you would like to shift it: "); //prompts for shift shiftStr = s.nextLine(); while (!checkIfStringIsNumber(shiftStr)) { //checks if shiftStr entered was a number System.out.print("That is not a valid answer. Enter how many letters you would like to shift the word: "); //re-prompts for shiftStr shiftStr = s.nextLine(); } shift = Integer.parseInt(shiftStr); //converts user input String to an int for (int i = 0; i < word.length(); i++) { //for loop to iterate through word temp = word.substring(i, i+1); //stores each letter into a temporary String index = alphabet.indexOf(temp); //finds index of the letter in the alphabet modIndex = (index + shift) % 26; //accounts for if the letter had an index later in the alphabet encrypted += alphabet.substring(modIndex, modIndex + 1); //adds each encrypted letter to the encrypted variable } System.out.println("The encrypted word is: " + encrypted); //outputs encrypted word } public static boolean checkIfStringIsNumber(String s) { //method to check if a string is a number try { Integer.parseInt(s); } catch (NumberFormatException e) { //if String isn't a number, return false return false; } return true; //if String is a number, return true } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.