EDIT: The code works now with no changes. Bizarre.
I am currently working my way through Stanford's CS106A Programming Methodology class and have just passed a lesson during which the teacher (Mehran Sahami, who is amazing) writes code for a Caesar cipher. Feeling inspired, I decided to write a little encryption program of my own, except this one generates a random shift for each letter, encrypts the string, then returns the encrypted string along with a string that contains the shift of each letter for decryption.
I wrote the code (in Java) below to do that, but I'm having trouble. Specifically, the code runs up to the point where I can enter a string (i.e., the console prompts with "What would you like to encrypt: " but after inputting and pressing enter the applet crashes and Eclipse highlights the "if" clause in encryptChar(char ch). I'm not sure why the code isn't working, so I'd really appreciate anybody who could explain to me what went wrong here.
I've tried to be extra diligent with comments and javadoc here, for readability, but let me know if anything I have done doesn't make sense or isn't clear.
import acm.program.*;
import acm.util.*;
@SuppressWarnings("serial")
public class randomPrivateEncrypt extends ConsoleProgram {
/** Takes a string from the user, encrypts it and returns it along with a randomly generated key for decryption.
* @param void
* @return void
*/
public void run() {
str = new String(readLine("What would you like to encrypt: ")); //Gets the string to be encrypted from the user.
println(encryptString(str)); //Encrypts the string, then prints it.
println("This is the random key used: " + key + "/n Keep it secret.");
//Prints the random key that is generated randomly term by term during encryptChar().
}
/** Encrypts a string.
* @param str - to be encrypted
* @return encryptedStr - the encrypted string
*/
private String encryptString(String str) {
String encryptedStr = "";
for(int i=0; i<str.length(); i++) { //For each character in the string
char ch = str.charAt(i); //Get the character
ch = encryptChar(ch); //Encrypt the character
encryptedStr += ch; //Add the character to the new string
}
return encryptedStr;
}
/** Encrypts a single character.
* @param ch - the character to be encrypted
* @return ch - the character, now encrypted
*/
private char encryptChar(char ch) {
if(Character.isUpperCase(ch)) {
int charKey = rgen.nextInt(1,26);
ch = (char) ('A' + (Character.toUpperCase(ch) - 'A' + charKey) % 26);
key += charKey;
key += ",";
} else {
key += 0;
}
return ch;
}
/** The String, later assigned to user input, that will be encrypted */
private String str;
/** The key, later assigned to the randomly generated sequence necessary to decrypt the message. */
private String key;
/** The random number generator used to generate the random key. */
private RandomGenerator rgen = RandomGenerator.getInstance();
}