2015-02-08 51 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