Unit 4 Team Homework
Iterations
public class CaesarCipher {
public static void main(String[] args) {
String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
String message1 = "Kfzb gly!";
String message2 = "zlab zlab zlab";
String message3 = "prmbozxifcoxdfifpqfzbumfxifalzflrp";
int shiftBy = 3 ; // showing how much to shift by
CaesarCipher caesarCipher = new CaesarCipher(); // instantiating CaesarCipher class
System.out.println("Decrypted Message1 : " + caesarCipher.decryptMessage(message1, shiftBy));
System.out.println("Decrypted Message2 : " + caesarCipher.decryptMessage(message2, shiftBy));
System.out.println("Decrypted Message3 : " + caesarCipher.decryptMessage(message3, shiftBy));
}
// method for decrypting given message by the shift int value
String decryptMessage(String input, int shiftBy){
int asciia =(int) 'a'; // assigning ascii values for a
String decryptMessage = "";
for(int i=0 ; i < input.length(); i++){
char c = input.charAt(i) ;
char newChar = c ;
// does decryption only for letters (not the exclamation mark, not spaces, etc.)
if( Character.isLetter(c) ){
int intValue = (int) c ; // finds the ascii value for given letter
int newValue = (intValue - asciia + shiftBy ) % 26 ; // assiging deciphered ascii value by subtracting the ascii value and adding the shift value
newValue = newValue + asciia ;
newChar = (char) newValue; // converting ascii value to new character
}
decryptMessage += newChar ;
}
return decryptMessage;
}
}
CaesarCipher.main(null);