gpt4 book ai didi

java - 为什么我的凯撒密码只能以小写形式工作

转载 作者:行者123 更新时间:2023-11-30 01:40:52 25 4
gpt4 key购买 nike

我是 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);

}
}

最佳答案

decrypt 方法中,对于小写字母,您可以编写:

char c = (char)(ch-shift);

对于大写字母,你可以写:

char c = (char)(ch+shift);

我非常确定这两行在 chshift 之间应该具有相同的运算符。如果您不想犯这样的错误,请尝试重构您的代码,以免出现重复的行。

关于java - 为什么我的凯撒密码只能以小写形式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60061996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com