我是JAVA编程的新手,我正在尝试创建一个凯撒密码加密/解密程序。不幸的是,我的程序仅适用于小写字母。我看不到哪里出了问题,我尝试了几次代码检查,但似乎无法找出问题所在。到目前为止,这是我的代码:
import java.util.Scanner;
public class CaesarCipher {
public static String encrypt(String plainText, int shift) {
if (shift > 26) {
shift = shift % 26;
} else if (shift < 0) {
shift = (shift % 26) + 26;
}
String cipherText = "";
int length = plainText.length();
for (int i = 0; i < length; i++) {
char ch = plainText.charAt(i);
if (Character.isLetter(ch)) {
if (Character.isLowerCase(ch)) {
char c = (char) (ch + shift);
if (c > 'z') {
cipherText += (char) (ch - (26 - shift));
} else {
cipherText += c;
}
} else if (Character.isUpperCase(ch)) {
char c = (char) (ch + shift);
if (c > 'Z') {
cipherText += (char) (ch - (26 - shift));
} else {
cipherText += c;
}
}
} else {
cipherText += ch;
}
}
return cipherText;
}
// Decrypt
public static String decrypt(String plainText, int shift) {
if (shift > 26) {
shift = shift % 26;
} else if (shift < 0) {
shift = (shift % 26) + 26;
}
String cipherText = "";
int length = plainText.length();
for (int i = 0; i < length; i++) {
char ch = plainText.charAt(i);
if (Character.isLetter(ch)) {
if (Character.isLowerCase(ch)) {
char c = (char) (ch - shift);
if (c < 'a') {
cipherText += (char) (ch + (26 - shift));
} else {
cipherText += c;
}
} else if (Character.isUpperCase(ch)) {
char c = (char) (ch + shift);
if (c < 'A') {
cipherText += (char) (ch + (26 - shift));
} else {
cipherText += c;
}
}
} else {
cipherText += ch;
}
}
return cipherText;
}
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.print("Enter your phrase: ");
String inputPlainText = input1.nextLine();
System.out.print("Enter your shift: ");
int shiftForPlainText = input1.nextInt();
String convertPlainText = encrypt(inputPlainText, shiftForPlainText);
System.out.println(convertPlainText);
System.out.print("Enter ciphertext: ");
String inputCipherText = input2.nextLine();
System.out.print("Enter shift: ");
int shiftForCipherText = input2.nextInt();
String convertCipherText = decrypt(inputCipherText, shiftForCipherText);
System.out.println(convertCipherText);
}
}
答案 0 :(得分:2)
在decrypt
方法中,小写为:
char c = (char)(ch-shift);
大写的是:
char c = (char)(ch+shift);
我非常确定,这两行在ch
和shift
之间应具有相同的运算符。如果您不想犯此类错误,请尝试重构您的代码,以确保没有重复的行。