。 。 .faulty凯撒密码java程序。 。 。

时间:2015-02-17 06:07:13

标签: java

这是Caesar密码程序,在此程序中解密过程完全有效,但加密过程有问题。帮我解决这个问题。

    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;
        }
        }
    }

这是程序打印ascii代码的值。

2 个答案:

答案 0 :(得分:0)

对于两种情况,只需在break;str.setCharAt(j, (char)(i+3))之后的内部循环中添加str.setCharAt(j, (char)(i-3))即可。那就没事了。

现在,如果我输入字符串aj,则incription将为dm。 如果我输入dm,则解密将为aj

答案 1 :(得分:0)

你的主要问题是你的内心循环。你在做什么基本上是:

  • 这是'a'吗?如果是,请添加3
  • 这是'b'吗?如果是,请添加3
  • 这是'c'吗?如果是,请添加3
  • 这是'd'吗?如果是,请添加3 ...

这完全没必要。只需取出角色,然后加3。

好的,不必要的并不意味着错误。如果出错,那就是你在添加3后继续检查。

如果角色是'a',你加3并得到'd'。循环中的三次迭代你会发现:这是一个'd',让我们添加3.不是你有'g'。三次迭代后,您将'g'添加3,依此类推。

所以,如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);

DTO。对于解密部分

相关问题