. . .错误的Caesar密码java程序。
这是凯撒密码程序,在这个程序中解密过程完全工作,但加密过程有问题。帮我解决这个问题. . .错误的Caesar密码java程序。,java,Java,这是凯撒密码程序,在这个程序中解密过程完全工作,但加密过程有问题。帮我解决这个问题 import java.io.IOException; import java.util.Scanner; public class test1 { public static void main(String[] args) throws IOException { int choice; System.out.println("Welc
import java.io.IOException;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) throws IOException {
int choice;
System.out.println("Welcome to Caesar cipher program");
System.out.println("enter the String");
StringBuffer str = new StringBuffer(new Scanner(System.in).nextLine());
System.out.println("enter your choice");
System.out.println("1. Encryption");
System.out.println("2. Decryption");
choice = (int) System.in.read();
switch(choice) {
case '1':
System.out.println("encrypting the String . . ." + str);
for(int j=0; j<str.length(); j++){
for(int i=0; i<256; i++) {
if(str.charAt(j) == (char)i){
str.setCharAt(j, (char)(i+3));
}
}
}
System.out.println("encrypted String . . ." + str);
break;
case '2':
System.out.println("Decrypting the String . . ." + str);
for(int j=0; j<str.length(); j++){
for(int i=0; i<256; i++) {
if(str.charAt(j) == (char)i){
str.setCharAt(j, (char)(i-3));
}
}
}
System.out.println("Decrypted String . . ." + str);
break;
}
}
}
import java.io.IOException;
导入java.util.Scanner;
公共类test1{
公共静态void main(字符串[]args)引发IOException{
智力选择;
System.out.println(“欢迎使用凯撒密码程序”);
System.out.println(“输入字符串”);
StringBuffer str=newStringBuffer(新扫描仪(System.in).nextLine());
System.out.println(“输入您的选择”);
System.out.println(“1.加密”);
System.out.println(“2.解密”);
choice=(int)System.in.read();
开关(选择){
案例“1”:
System.out.println(“加密字符串…”+str);
对于(int j=0;j只需在str.setCharAt(j,(char)(i+3))
和str.setCharAt(j,(char)(i-3))
之后的内部循环中添加break;
,就可以了
现在,如果我输入stringaj
,那么说明将是dm
。
如果我输入dm
,说明将是aj
您的主要问题是您的内部循环。您所做的基本上是:
- 这是“a”吗?如果是,添加3
- 这是“b”吗?如果是,添加3
- 这是“c”吗?如果是,添加3
- 这是d吗?如果是,加3
这完全没有必要。只需选取角色,然后添加3
好的,不必要并不意味着错误。错误的地方是在添加3后继续检查
如果角色是“a”,则添加3并获得“d”。在循环中三次迭代后,您会发现:这是一个“d”,让我们添加3。而不是获得“g”。三次迭代后,您将3添加到“g”,依此类推
所以,正如AJ所建议的,一个中断声明会有所帮助
另一方面:最好的解决方案是失去内部循环:
System.out.println("encrypting the String . . ." + str);
for(int j=0; j<str.length(); j++){
char c = str.charAt(j);
str.setCharAt(j, (char)(c+3));
}
System.out.println("encrypted String . . ." + str);
System.out.println(“加密字符串…”+str);
对于(int j=0;j)“程序解密过程完全工作,但加密过程有问题”没有帮助。问题是什么?加密过程有问题不是一个有用的问题描述。您是否得到错误?请包括示例输入加上预期和实际输出。顺便说一句,您的内部for循环(在这两种情况下)完全没有必要。