Skip to content

Instantly share code, notes, and snippets.

@charlesreid1
Last active January 31, 2017 18:09
Show Gist options
  • Save charlesreid1/b37c30d2c4708e64deabd83d70012d00 to your computer and use it in GitHub Desktop.
Save charlesreid1/b37c30d2c4708e64deabd83d70012d00 to your computer and use it in GitHub Desktop.
Caesar Cipher Solution - CSC 142
public class CaesarSolution {
public static String caesarShift(String message, int key, boolean doEncryption) {
message = message.toUpperCase();
message = message.replace(" ","");
// This is the variable storing the encrypted/decrypted message
String message2 = "";
for( int j = 0; j < message.length(); j++ ) {
char c, c2;
int ix, ix2;
c = message.charAt(j);
// Deal with non-letter characters using user-specified strategy
if( c >= 'A' && c <= 'Z' ) {
// Apply Caesar shift to letters
ix = (int)(c - 'A');
if( doEncryption ) {
ix2 = (ix + key)%26;
} else {
// have to add 26 to ensure everything positive, because -1 mod 26 does not become 25
ix2 = (26 + ix - key)%26;
}
c2 = (char)('A' + ix2);
// append to message
message2 += c2;
}
// ignore punctuation
}
return message2;
}
public static void main(String[] args) {
System.out.println( caesarShift("Gaul is divided into three parts", 5, true) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment