我目前正在嘗試編寫一個基本的加密程序。我大部分都在努力工作。它只是不夠我正在工作。 基本上,用戶輸入一個短語,一個移位量(例如5個,前面是5個字母),並且該程序加密該短語。 例如,如果用戶輸入「紅色」的偏移量爲5,程序應該打印出來:WJI 但是,我得到的程序使用Unicode,所以它打印出相應的Unicode字符,所以我是獲取符號,例如我的加密中的「{,:」。它仍然有效,請注意,但不是我想要的方式。Java密碼移位字母
這裏是我的代碼:
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.我怎樣才能讓字母「循環」。例如,這個字母是Z,換一個2會使它變成「B」?
提示:模運算符:''% – 2015-02-08 15:39:56