|
| 1 | +import edu.duke.*; |
| 2 | + |
| 3 | +public class CaesarCipher { |
| 4 | + public String encrypt(String input, int key) { |
| 5 | + //Make a StringBuilder with message (encrypted) |
| 6 | + StringBuilder encrypted = new StringBuilder(input); |
| 7 | + //Write down the alphabet |
| 8 | + String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; |
| 9 | + //Compute the shifted alphabet |
| 10 | + String shiftedAlphabet = alphabet.substring(key)+ |
| 11 | + alphabet.substring(0,key); |
| 12 | + //Count from 0 to < length of encrypted, (call it i) |
| 13 | + for(int i = 0; i < encrypted.length(); i++) { |
| 14 | + //Look at the ith character of encrypted (call it currChar) |
| 15 | + char currChar = encrypted.charAt(i); |
| 16 | + //Find the index of currChar in the alphabet (call it idx) |
| 17 | + int idx = alphabet.indexOf(currChar); |
| 18 | + //If currChar is in the alphabet |
| 19 | + if(idx != -1){ |
| 20 | + //Get the idxth character of shiftedAlphabet (newChar) |
| 21 | + char newChar = shiftedAlphabet.charAt(idx); |
| 22 | + //Replace the ith character of encrypted with newChar |
| 23 | + encrypted.setCharAt(i, newChar); |
| 24 | + } |
| 25 | + //Otherwise: do nothing |
| 26 | + } |
| 27 | + //Your answer is the String inside of encrypted |
| 28 | + return encrypted.toString(); |
| 29 | + } |
| 30 | + public void testCaesar() { |
| 31 | + int key = 17; |
| 32 | + FileResource fr = new FileResource(); |
| 33 | + String message = fr.asString(); |
| 34 | + String encrypted = encrypt(message, key); |
| 35 | + System.out.println(encrypted); |
| 36 | + String decrypted = encrypt(encrypted, 26-key); |
| 37 | + System.out.println(decrypted); |
| 38 | + } |
| 39 | +} |
| 40 | + |
0 commit comments