Search code examples
javaencryptioncaesar-cipher

Calculating distance between plaintext and ciphertext of a Caesar cipher


I have a text file like this:

GASDGHSDH BVNYBCNYC
HDFS UQSF
CXVN KFDV
SHDF APLN
HDSFHS OKZMOZ
SAH YGN
DSHF HWLJ
REEW TGGY
SGDFH AOLNP
DHSF EITG
GSDHASD IUFJCUF
DHFSDF KOMZKM
DSFH SHUW

And I don't know decryption key. For Example: HDFS UQSF Key == 13

because U - H == 13

Ok. I write code:

public static int codeJC(String first, String twice){
    first = first.toLowerCase();
    twice = twice.toLowerCase();
    char a = first.charAt(0);
    char b = twice.charAt(0);


    int r = 0;
    if((a-b) >0){
        r = a-b;
    }else{
        r = b-a;

    }

    return r;


}

But if:

System.out.println(codeJC("Z", "A")); //this return 25 !?!?!?!?
System.out.println(codeJC("C", "F")); //this return good value

Why when a < b gets a bad value?


Solution

  • if ((a - b) > 0) {
        r = 26 - (a - b);
    } else {
        r = b - a;
    }