Skip to content

Instantly share code, notes, and snippets.

@desmondrawls
Created March 30, 2013 17:20
Show Gist options
  • Save desmondrawls/5277532 to your computer and use it in GitHub Desktop.
Save desmondrawls/5277532 to your computer and use it in GitHub Desktop.
Caesar Cipher
import acm.program.*;
public class Caesar extends ConsoleProgram {
private char encryptChar (char ch, int key){
if (Character.isUpperCase(ch)) {
return((char)('A' + ((ch - 'A' + key)%26)));
}
return ch;
}
private string encryptString (string str, int key) {
if (key<0){
key = 26 - (-key % 26);
}
string encrypted = "";
for (int i = 0; i < str.length; i++){
char ch = str.charAt(i);
result += encryptChar (ch, key);
}
return encrypted;
}
public void run() {
int key = readInt ("Enter Key: ");
string plaintext = readLine ("Enter Text: ");
string cipher = encryptString(plaintext, key);
println(cipher);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment