I am to generate a cipher alphabet (based on Caesar Cipher) given the user-inputted shift key, and my code seems to be wrong.
I don't understand what's wrong with my cipherAlphabet method because whenever I try to test out the result, it just ends up giving me an error of "java.lang.ArrayIndexOutOfBoundsException: 26."
So, it probably has something to do with going past the arrays I set, but I cannot see this. I know this is probably something really simple, but could someone help me out?
P.S. - I tried looking for existing hints on SO and other websites for some help, but to no avail.
I would do all the conversions and encryption in one method, but I can't do that unforunately (apparently, I have to do this). Here's what I have:
private String message;
private static int shiftKey;
public static final String[] ALPHABET = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "N",
"M", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
public static String[] cipherAlphabet = new String[ALPHABET.length];
/**
* Constructor for objects of class CaesarShiftEncryption
*/
public CaesarShiftEncryption(String m, int shift)
{
message = m;
shiftKey = shift;
}
public static String[] cipherAlphabet()
{
for(int i = 0; i < ALPHABET.length; i++)
{
if(i >= 23)
{
cipherAlphabet[i] += ALPHABET[26 - shiftKey];
}
else
{
cipherAlphabet[i] += ALPHABET[i + shiftKey];
}
}
return cipherAlphabet;
}
You need to start over! Try something like this, using the mod operation, you'll restart at the beginning of the alphabet, if you happen to hit the end
cipherAlphabet[i] += ALPHABET[(i + shiftKey) % ALPHABET.length]