2015-02-08 54 views
0

我目前正在嘗試編寫一個基本的加密程序。我大部分都在努力工作。它只是不夠我正在工作。 基本上,用戶輸入一個短語,一個移位量(例如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」?

+1

提示:模運算符:''% – 2015-02-08 15:39:56

回答

0

而不是

shift = cipher.charAt(i) - rotation 

嘗試

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

非常感謝你 - 這個工作。你介意給我解釋一下嗎?我知道我們正在添加或減少字母,但模數運算符在這裏做什麼呢? (對不起,初學者編碼器在這裏) – 2015-02-08 15:47:37

+0

你不能在ascii中直接計算模塊25(因爲你希望它在ascii值'A'到'Z'之間而不在ascii值0到25之間)。所以,你首先計算'A'的偏移量(並存儲在'tmp'中)。然後,您可以使用模運算符來確保計算環繞大約25.(第二行)。模運算的結果在0到25之間,這意味着您需要添加'A'使其成爲ASCII值。 (第三行)。 – aioobe 2015-02-08 15:58:00