Java Shift Caesar Cipher by shift
spaces.
Restrictions:
- Only works with a positive number in the shift parameter.
- Only works with shift less than 26.
- Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
- Does a cast number to character, so it will fail with anything but ascii letters.
- Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
- Code violates the DRY (don’t repeat yourself) principle by repeating the calculation more than it has to.
Pseudocode:
- Loop through each character in the string.
- Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
- If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
- Append the character onto a new string. Return the string.
Function:
String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
How to invoke it:
System.out.println(cipher("abc", 3)); //prints def
System.out.println(cipher("xyz", 3)); //prints abc