-3

我正在尝试创建一个基本的加密程序,将字符值转换为数字形式,添加“密钥”,然后将它们转换回字符形式,从而加密单词。

但是我不知道如何使数值为 90 或更大(char Z),循环回 65(char A)。

public class Encode {

    /**
     * Main method - this does not need to be changed at all.
     */
    public static void main(String[] args) {
        testing();
        userInteraction();
    }

    /**
     * This method is used to test the encrypt method.
     */
    public static void testing() {

        String testMessage1 = "test";
        int testKey1 = 11;
        String result = encrypt(testMessage1, testKey1);
        System.out.println("Encrypted result: "+result);
    }

    /**
     * This method changes each character in a String to a
     * different character based on the key passed in as
     * an integer. The new String created by the encryption
     * process is returned.
     *
     * @param message   the String to be encoded
     * @param key       the integer value used for encryption
     * @return          a new encoded String
     */
    public static String encrypt(String message, int key) {
        System.out.println("encoding: "+message+", with key: "+key);
        String encodedMessage = "";
        message=message.toUpperCase();

        int length = message.length();
        for(int i=0;i<length;i++)
        {
            int characterValue = (int)message.charAt(i);
            characterValue = characterValue + key;
                if(characterValue>90)
                {
                    characterValue = (65 + key ); // <---- What needs to go here? In order to make value loop back to A.
                }

            char myChar = (char)characterValue;
            encodedMessage=encodedMessage+myChar;
        }


        return encodedMessage;
    }
4

1 回答 1

0

首先,让我们先说您的加密不明确。也就是说,更改characterValue = (65 + key );characterValue = ((characterValue - 90) + 65);
Also, you were added the key on 两次characterValue>90

好吧,让我用例子来解释一下。
在该行characterValue = characterValue + key;中,您已经将密钥添加到了字母中,因此我将其从if. 我不认为这部分需要一个例子。

下一部分,总和本身:
假设有人键入 AZTEST,键为 11,结果应该是(添加键并重新开始,如果大于 90):LLFPEF

A(65):(76)L
Z(90):(101->76)L
T(84):(95->70)F
E(69):(80)P
S(83):(94->69)E
T(84):(95->70)F

以“S”为例,我们有 83 + 11 = 94。94 大于 90,所以我们要做的是:首先,我们找出它超过了多少 (94 - 90 = 4)。现在我们有了这个数字,我们只需要重新开始计数。A=65,所以 65+4=69。69 = E。

问题是 Z 将变得与另一个值相同。我看到的唯一密钥 Z 与 A 不同,在这种情况下,密钥 = 0,但加密会被破坏,因为原始文本没有变化。

于 2015-10-05T01:47:17.447 回答