解密是解决问题的原因。
public static void encrypt(Scanner scan, PrintWriter out, String key) throws IOException {
while(scan.hasNextLine()){
String lineRead = scan.nextLine();
for(int i=0; i < lineRead.length(); i++){
char c = lineRead.charAt(i);
out.print(shiftUpByK(c, key.charAt(i%key.length()) - 'a' ));
}
out.println();
}
}
public static void decrypt(Scanner scan, PrintWriter out, String key) {
while(scan.hasNextLine()){
String lineRead = scan.nextLine();
for(int i = 0; i < lineRead.length(); i++){
char c = lineRead.charAt(i);
out.print(shiftDownByK(c,key.charAt(i%key.length())));
}
out.println();
}
}
public static final int NUM_LETTERS = 26;
public static char shiftUpByK(char c, int k) {
if ('a' <= c && c <= 'z')
return (char) ('a' + (c - 'a' + k) % NUM_LETTERS);
if ('A' <= c && c <= 'Z')
return (char) ('A' + (c - 'A' + k) % NUM_LETTERS);
return c; // don't encrypt if not an alphabetic character
}
public static char shiftDownByK(char c, int k) {
return shiftUpByK(c, NUM_LETTERS - k);
}