2016-10-19 100 views
0

这里有一个Java代码凯撒的密码凯撒的密码

import java.util.*; 

public class Main { 

public static void main(String[] args) { 
    Scanner stdin = new Scanner(System.in); 
    int length = stdin.nextInt(); 
    String text = stdin.next(); 
    int shift = stdin.nextInt(); 

    for(int i = 0; i < length; i++) { 
     char c = text.charAt(i); 
     if(c >= 'a' && c <= 'z') { 
      System.out.print((char)(((int)c - (int)'a' + shift) % 26 + (int)'a')); 
     } else if(c >= 'A' && c <= 'Z') { 
      System.out.print((char)(((int)c - (int)'A' + shift) % 26 + (int)'A')); 
     } else { 
      System.out.print(c); 
     } 
    } 
    stdin.close(); 
} 
} 

,我不明白是什么在这行代码

System.out.print((char)(((int)c - (int)'a' + shift) % 26 + (int)'a')); 

为什么发生 - (int)的 'A'

回答

1

它的ASCII值..字母a的ascii值为97, A的ascii值为65.

我希望你能理解ceaser密码是如何工作的。

,如果你有ABCD你原来的文字和你想要做的1移位申请凯撒密码,这意味着A将B,B为C,C是d,d将是E.

长度是您的字符串长度,文本是您的原始文本,转换是您希望应用ceaser密码的字母数量。

让作为示例文本:ABCD

带换档1

现在让我们假设C值是 '一'

因此该语句是(int)c - (int)'a' + shift) % 26 + (int)'a')

通常做(97 -97 + 1)%26 + 97

(1%26)+97 
1+97 
98 

这是ascii e b。这就是为什么在你的代码的整个操作转换末为char:

**(char)**(((int)c - (int)'a' + shift) % 26 + (int)'a') 

希望这是有道理的

3

为了使%26正确地旋转编码字符,当移动将它推到'z'以上时,您需要处理0-25值。 'a' - 'z'的ASCII值是97-122,这使得旋转困难。通过从被移位的字符中减去'a',将字符映射到0-25的值,使用%26可以进行旋转。

1

为“最大汉普顿”之称,字母从97 ASCII table开始值(在小写字母的情况下)。因此,如果例如你有字母c='p',那么c = 112.也'a'= 97,所以'p' - 'a'= 112-97 = 15(注意:p是字母16中的位置)。

现在我们增加了班次(虽然现在p已经移动了1步,但我们会立即修复它)。让换档是3(我们希望P-> S)

现在我们得到15 + 3 = 18 18%26 = 18。

现在

用于修复:18 + 'A'= 18+ 97 = 115 ='s'(1回到这里)

并完成:)