Java 密码转换字母

Java Cipher Shifting Letters

我目前正在尝试编写一个基本的加密程序。在大多数情况下,我让它工作。它只是不像我想要的那样工作。 基本上,用户输入一个短语,一个移位量(例如 5,向前移动 5 个字母),然后程序对该短语进行加密。 例如,如果用户输入 "red" 并移动 5,程序应打印出:WJI 但是,我让程序使用 Unicode,所以它打印出相应的 Unicode 字符,所以我在加密中得到符号,例如“{,:”。请注意,它仍然有效,但不是我正在寻找的方式。

这是我的代码:

import javax.swing.*;
public class SimpleEncryption {

/**
 * @param args the command line arguments
 */
static int shift;
public static void main(String[] args) {
   String cipher = JOptionPane.showInputDialog(null, "Please enter a sentence or word that you wish to encode or decode. This program uses"
           + " a basic cipher shift.");
  String upperCase = cipher.toUpperCase();
   char[] cipherArray = cipher.toCharArray(); 
   String rotationAmount = JOptionPane.showInputDialog(null, "Please enter a shift amount.");
   int rotation = Integer.parseInt(rotationAmount);
   String encryptOrDecrypt = JOptionPane.showInputDialog(null, "Please choose whether to encrypt or decrypt this message. \n"
           + "Encrypt - press 1\nDecrypt - press 2");
   int choice = Integer.parseInt(encryptOrDecrypt);
   int cipherLength = cipherArray.length;

   if (choice == 1) { //if the user chooses to encrypt their cipher
       System.out.println("The original phrase is: "+upperCase);
       System.out.println("ENCRYPTED PHRASE:");
       for (int i = 0; i < cipherLength; i++) {
       shift = (upperCase.charAt(i) + rotation);
       System.out.print((char)(shift));
       }
       System.out.println(" ");
   }
       else if (choice == 2) {
          System.out.println("DECRYPTED PHRASE:");
               for (int i = 0; i < cipherLength; i++) {
                  shift = (cipher.charAt(i) - rotation);
                   System.out.print((char)(shift));
               }


               }


   }

}

感谢任何和所有建议。另外,假设用户输入了 25 的移位值。如何让字母表变为 "loop" 左右。例如,字母是 Z,移位 2 会使它成为 "B"?

而不是

shift = cipher.charAt(i) - rotation

尝试

int tmp = cipher.charAt(i) - 'A';    // Offset from 'A'
int rotated = (tmp - rotation) % 26; // Compute rotation, wrap at 26 for chars
shift = rotated + 'A';               // Add back offset from 'A'