Hey so recently I got tasked with creating an app that reads a message and ecrypts it with the Caesar cipher in Java.
I didn't really have a problem until I came to the part where adding the numberic cipher would take you over letters a-z/A-Z into special symbols and I did not really know what to do.
Here is the code of my solution:
private String caesarCipher(String message) {
Scanner input = new Scanner(System.in);
StringBuilder cipher = new StringBuilder();
char ch;
int key;
System.out.print("Enter a key: ");
key = Integer.parseInt(input.nextLine());
for(int i = 0; i < message.length(); i++) {
ch = message.charAt(i);
if(ch >= 'a' && ch <= 'z'){
ch = (char)(ch + key);
if(ch > 'z'){
ch = (char)(ch - 'z' + 'a' - 1);
}
cipher.append(ch);
}
else if(ch >= 'A' && ch <= 'Z'){
ch = (char)(ch + key);
if(ch > 'Z'){
ch = (char)(ch - 'Z' + 'A' - 1);
}
cipher.append(ch);
}
else {
cipher.append(ch);
}
}
return cipher.toString();
}
Could someone please explain to me the process and reasoning behind the following statement:
if(ch > 'z'){
ch = (char)(ch - 'z' + 'a' - 1);
}