我创建了一个程序,它接受消息的输入以及向前或向后循环的字母数的输入。这都是有效的,除了我不知道如何从 A 向后循环到 Z。例如,每当我尝试从 A 向后循环时,我都会得到一个值,例如 ^。我不知道如何循环回 Z。这是通过将字符转换为 unicode 值来完成的。我的代码如下:
package caesarcypher;
import java.util.Scanner;
public class CaesarCypher {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int cycle,i,n;
String message;
String str1="";
String str2="";
System.out.println("Enter the plaintext");
message=sc.nextLine();
message=message.toLowerCase();
n=message.length();
char ch1[]=message.toCharArray();
char ch3,ch4;
System.out.println("Enter the value by which each letter of the string is to be shifted");
cycle=sc.nextInt();
System.out.println();
System.out.println("Encrypted text is");
for(i=0;i<n;i++)
{
if(Character.isLetter(ch1[i]))
{
ch3=(char)(((int)ch1[i]+cycle-97)%26+97);
//System.out.println(ch1[i]+" = "+ch3);
str1=str1+ch3;
}
else if(ch1[i]==' ')
{
str1=str1+ch1[i];
}
}
System.out.println(str1);
System.out.println();
System.out.println("Decrypted text is");
char ch2[]=str1.toCharArray();
for(i=0;i<str1.length();i++)
{
if(Character.isLetter(ch2[i]))
{
if(((int)ch2[i]-cycle)<97)
{
ch4=(char)(((int)ch2[i]-cycle-97+26)%26+97);
}
else
{
ch4=(char)(((int)ch2[i]-cycle-97)%26+97);
}
str2=str2+ch4;
}
else if(ch2[i]==' ')
{
str2=str2+ch2[i];
}
}
System.out.println(str2);
}
}
这是因为模算术的工作原理。
(-1) % 26 = -1
因此,当您将其添加到 97 时,您仍然在 A 之前。 循环回 1 的示例。
('A' + cycle - 97) % 26 + 97
(97 -1 -97) % 26 + 97
-1%26 + 97
-1 + 97. <----- NOT +25
最简单的解决方案是,如果它是负数,则只需将 26 加到 cycle
,尽管它仍然会在输入时中断,例如 -50。 您似乎已经在解密部分中解决了类似的问题。