I'm creating a program to do a Caesar Cipher, which shifts the letters in a word one time when I hit enter, and prompts the user to shift again or quit.
It works until I get to 23 shifts, then it starts using non-letter symbols for some reason, and I'm not sure why this is happening.
Any suggestions? Here is the code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Cipher {
public static void main(String[] args) {
// encrypted text
String ciphertext;
// input from keyboard
Scanner keyboard = new Scanner(System.in);
if (args.length > 0) {
ciphertext = "";
try {
Scanner inputFile = new Scanner(new File(args[0]));
while (inputFile.hasNext())
ciphertext += inputFile.nextLine();
} catch (IOException ioe) {
System.out.println("File not found: " + args[0]);
System.exit(-1);
}
} else {
System.out.print("Please enter text--> ");
ciphertext = keyboard.nextLine();
}
// -----------------------------------------------------------------
int distance = 0; // how far the ciphertext should be shifted
String next = ""; // user input after viewing
while (!next.equals("quit")) {
String plaintext = "";
distance += 1;
for (int i = 0; i < ciphertext.length(); i++) {
char shift = ciphertext.charAt(i);
if (Character.isLetter(shift)) {
shift = (char) (ciphertext.charAt(i) - distance);
if (Character.isUpperCase(ciphertext.charAt(i))) {
if (shift > '0' && shift < 'A') {
shift = (char) (shift + 26);
plaintext += shift;
} else {
plaintext += shift;
}
}
if (Character.isLowerCase(ciphertext.charAt(i))) {
if (shift > '0' && shift < 'a' && ciphertext.charAt(i) < 't') {
shift = (char) (shift + 26);
plaintext += shift;
} else {
plaintext += shift;
}
}
} else {
plaintext += shift;
}
}
System.out.println(ciphertext);
// At this point, plaintext is the shifted ciphertext.
System.out.println("distance " + distance);
System.out.println(plaintext);
System.out.println("Press enter to see the next option,"
+ "type 'quit' to quit.");
next = keyboard.nextLine().trim();
}
System.out.println("Final shift distance was " + distance + " places");
}
}