I have a problem when I'm trying to decode an encrypted message. It decrypts almost everything as it should be, but when I try to decrypt 'w x y z' (all lower case), it doesn't work properly. It only decrypts those letters when they are UPPERCASE. What did I do wrong?
@SuppressWarnings("unused")
public static void main(String[] args) {
String message = "ABCDEFGHILMNOPQRSTU hello giordano WORLD HOW wxyZ XyZ XYZ YOU xyz";
System.out.println(message);
String encr = encrypt(message);
String decr = decrypt(encr);
System.out.println(encr + "\n" + decr);
}
@SuppressWarnings("unused")
private static String encrypt(String message) {
StringBuilder temp = new StringBuilder();
for(int i=0; i<message.length(); i++) {
char c = (char)(message.charAt(i) + 3);
if(c >= 'x') {
c = (char)(message.charAt(i) - 23);
} else {
c = (char)(message.charAt(i) + 3);
}
temp.append(c);
}
return temp.toString();
}
private static String decrypt(String message) {
StringBuilder temp = new StringBuilder();
for(int i=0; i<message.length(); i++) {
char c = (char)(message.charAt(i) - 3);
// HELLO WORLD
// KHOOR ZRUOG
if(c > 'x') {
c = (char)(message.charAt(i) + 26);
} else {
c = (char)(message.charAt(i) - 3);
}
temp.append(c);
}
return temp.toString();
}
OUTPUT:
Text: ABCDEFGHILMNOPQRSTU hello giordano WORLD HOW wxyZ XyZ XYZ YOU xyz
Encrypted: DEFGHIJKLOPQRSTUVWX#khoor#jlrugdqr#ZRUOG#KRZ#`ab]#[b]#[\]#\RX##abc
Decrypted: ABCDEFGHILMNOPQRSTU hello giordano WORLD HOW ]^_Z X_Z XYZ YOU ^_`
EXPECTED OUTPUT:
Text: ABCDEFGHILMNOPQRSTU hello giordano WORLD HOW wxyZ XyZ XYZ YOU xyz
Encrypted: DEFGHIJKLOPQRSTUVWX#khoor#jlrugdqr#ZRUOG#KRZ#`ab]#[b]#[\]#\RX##abc
Decrypted: ABCDEFGHILMNOPQRSTU hello giordano WORLD HOW wxyZ XyZ XYZ YOU xyz