|
| 1 | +import java.util.ArrayList; |
| 2 | + |
| 3 | +public class CaesarShift { |
| 4 | + private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //Encapsulate and make the alphabet immutable |
| 5 | + private static int key = 25; //Initialize and encapsulate the shift key |
| 6 | + private static String encryptedMsg; //Create and encapsulate the message container |
| 7 | + private static String decryptedMsg; |
| 8 | + |
| 9 | + public String encrypt(String encryptMsg){ |
| 10 | + String upCased = encryptMsg.toUpperCase(); |
| 11 | + char[] upCasedArrs = upCased.toCharArray();//split the string to a character array |
| 12 | + ArrayList<Character> encryptedChars = new ArrayList<Character>(); |
| 13 | + |
| 14 | + //loop through the character array |
| 15 | + for(Character character : upCasedArrs ){ |
| 16 | + int index = ALPHABET.indexOf(character.toString());//get the character rank in the alphabet |
| 17 | + int encryptedCharIndex = Math.floorMod((index+key),26);//shift the character using the key and get the new characters rank in the alphabet |
| 18 | + encryptedChars.add(ALPHABET.charAt(encryptedCharIndex));//get the character from the alphabet rank and add it to the char array |
| 19 | + encryptedMsg = encryptedChars.toString().replaceAll("\\[|\\]|\\s","").replaceAll(",","");//convert and cleanup the char array to a string |
| 20 | + } |
| 21 | + return encryptedMsg; |
| 22 | + } |
| 23 | + |
| 24 | + public String decrypt(String decryptMsg) { |
| 25 | + String upCased = decryptMsg.toUpperCase(); |
| 26 | + char[] upCasedArrs = upCased.toCharArray();//split the string to a character array |
| 27 | + ArrayList<Character> decryptedChars = new ArrayList<Character>(); |
| 28 | + |
| 29 | + //loop through the character array |
| 30 | + for (Character character : upCasedArrs) { |
| 31 | + int index = ALPHABET.indexOf(character.toString());//get the character rank in the alphabet |
| 32 | + int decryptedCharIndex = Math.floorMod((index - key), 26);//shift the character using the key and get the new characters rank in the alphabet |
| 33 | + decryptedChars.add(ALPHABET.charAt(decryptedCharIndex));//get the character from the alphabet rank and add it to the char array |
| 34 | + decryptedMsg = decryptedChars.toString().replaceAll("\\[|\\]|\\s", "").replaceAll(",", "");//convert and cleanup the char array to a string |
| 35 | + } |
| 36 | + return decryptedMsg; |
| 37 | + |
| 38 | + } |
| 39 | + |
| 40 | +} |
0 commit comments