计算Caesar密码的明文和密文之间的距离

时间:2016-06-07 09:08:42

标签: java encryption caesar-cipher

我有一个这样的文本文件:

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

我不知道解密密钥。例如: HDFS UQSF 键== 13

因为U - H == 13

确定。我写代码:

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;


}

但是如果:

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

为什么当< b得到一个坏的价值?

1 个答案:

答案 0 :(得分:-1)

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