Java 为什么我的凯撒密码只能用小写字母
我是JAVA编程新手,我正在尝试创建一个caesar密码加密/解密程序。不幸的是,我的程序只在小写情况下工作。我看不出哪里出了问题。我试着检查我的代码好几次,但我似乎没有发现问题。以下是我目前的代码:Java 为什么我的凯撒密码只能用小写字母,java,Java,我是JAVA编程新手,我正在尝试创建一个caesar密码加密/解密程序。不幸的是,我的程序只在小写情况下工作。我看不出哪里出了问题。我试着检查我的代码好几次,但我似乎没有发现问题。以下是我目前的代码: import java.util.Scanner; public class Caes
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);
}
}
import java.util.Scanner;
公共类密码{
公共静态字符串加密(字符串明文,int移位){
如果(移位>26){
班次=班次%26;
}如果(移位<0){
班次=(班次%26)+26;
}
字符串密文=”;
int length=纯文本.length();
对于(int i=0;i'z'){
密文+=(字符)(ch-(26-shift));
}否则{
密文+=c;
}
}如果(Character.isUpperCase(ch)){
字符c=(字符)(ch+shift);
如果(c>'Z'){
密文+=(字符)(ch-(26-shift));
}否则{
密文+=c;
}
}
}否则{
密文+=ch;
}
}
返回密文;
}
//解密
公共静态字符串解密(字符串明文,int移位){
如果(移位>26){
班次=班次%26;
}如果(移位<0){
班次=(班次%26)+26;
}
字符串密文=”;
int length=纯文本.length();