简体   繁体   中英

The error about string encryption scheduling : (char) (ch + key) % 26

Problem one: Here are two code spinner. Code A runs wrong. But I do not know what is wrong.

Problem two: code B is right.but I do not understand why it need to delete 'A'. then add 'A' after fmod. What is the effect about 'A'? Why it has the error after delete?

Code A (ch + key) % 26 )

Code B ('A' + ((ch -'A' + key) % 26))

 public void run() {    
        setFont("Arial-PLAIN-24");
        String line = readLine ("Enter line: ");
        int key = readInt ("Enter key: ");
        String siphertext = encryptCaesar(line , key);
        println("The result is: " + siphertext);
        String newplain = encryptCaesar(siphertext , -key);
        println("newplain:" + newplain);    
    }

    private String encryptCaesar(String str , int key){
        if(key < 0){
            key = 26 - ( -key % 26 );
        }

        String result = "";
        for(int i = 0; i < str.length(); i++){
            char ch = str.charAt(i);        
            result += encryptChar(ch,key);
        }
        return result;
    }

    private char encryptChar(char ch, int key){
        if(Character.isUpperCase(ch)){
            return ( (char) ('A' + ((ch -'A' + key) % 26)) );
        }
        return ch;
    }

15.7.3 Remainder Operator %

... It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive.

An example is then provided:

int e = (-5)%3; // -2
int f = (-5)/3; // -1
System.out.println("(-5)%3 produces " + e +
                   " (note that (-5)/3 produces " + f + ")");

If the result of ((ch -'A' + key) % 26)) is negative, then wouldn't the result of (char) ('A' + ((ch -'A' + key) % 26)) be some non-alphabet character? Perhaps you need to add 26 to any negative values or find the absolute value, so that they're positive and result in actual alphabet characters.

'A' is added to make sure the result of "encryptChar" method, is a valid character in ASCII range 64 to 90 , which is A (CAPITAL) to Z (CAPITAL) . Refer the ASCII table here .

In your code subtracting of 'A' can also be ignored. That is the below will also work,

('A' + ((ch + key) % 26))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM