如何在凯撒密码中包含“ _”

时间:2019-09-16 22:30:21

标签: java caesar-cipher

我有一个用于Java的终止密码,它工作正常,但是我尝试解码的消息的空格为"_"。它们落在z之后,并且在移动1时应为“ A”。我该如何将其添加到代码中?我试着用"_"替换“ z”,以为那样容易,但是随后将"_"更改为"`"

import java.util.*;
public class CaesarCipherProgram {
    public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    System.out.println(" Input the ciphertext message : ");
    String ciphertext = sc.nextLine();
    System.out.println(" Enter the shift value : ");
    int shift = sc.nextInt();
    String decryptMessage = "";
    for(int i=0; i < ciphertext.length();i++)  

    {
        // Shift one character at a time
        char alphabet = ciphertext.charAt(i);
        // if alphabet lies between a and z 
        if(alphabet >= 'a' && alphabet <= 'z')
        {
            // shift alphabet
            alphabet = (char) (alphabet - shift);

            // shift alphabet lesser than 'a'
            if(alphabet < 'a') {
                //reshift to starting position 
                alphabet = (char) (alphabet-'a'+'z'+1);
            }
            decryptMessage = decryptMessage + alphabet;
        }    
            // if alphabet lies between A and Z
        else if(alphabet >= 'A' && alphabet <= 'Z')
        {
         // shift alphabet
            alphabet = (char) (alphabet - shift);

            //shift alphabet lesser than 'A'
            if (alphabet < 'A') {
                // reshift to starting position 
                alphabet = (char) (alphabet-'A'+'Z'+1);
            }
            decryptMessage = decryptMessage + alphabet;            
        }
        else 
        {
         decryptMessage = decryptMessage + alphabet;            
        } 
      }
      System.out.println(" decrypt message : " + decryptMessage);
   }
}

1 个答案:

答案 0 :(得分:0)

您可以像这样重新编写逻辑:

private static final String KEY = "abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static String shift(String input, int amount) {
    final int keyLen = KEY.length();
    final int shift = (amount % keyLen + keyLen) % keyLen;
    char[] buf = input.toCharArray();
    for (int i = 0; i < buf.length; i++) {
        int idx = KEY.indexOf(buf[i]);
        if (idx != -1)
            buf[i] = KEY.charAt((idx + shift) % keyLen);
    }
    return new String(buf);
}

测试

System.out.println(shift("Hello World", -1));
System.out.println(shift("Hello World", 0));
System.out.println(shift("Hello World", 1));
System.out.println(shift("Hello World", 2));
System.out.println(shift("Hello World", 3));
System.out.println(shift("Hello World", 30));
System.out.println(shift(shift("Hello World", 30), -30));
System.out.println(shift(shift("Hello World", 30), 23));

输出

Gdkkn Vnqkc
Hello World
Ifmmp Xpsme
Jgnnq Yqtnf
Khoor Zruog
lHOOR _RUOG
Hello World
Hello World