国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

JAVA實現(xiàn)caesar凱撒加密算法

2019-11-26 15:47:29
字體:
供稿:網(wǎng)友

復(fù)制代碼 代碼如下:

public class Caesar {
 public static final String SOURCE = "abcdefghijklmnopqrstuvwxyz";
 public static final int LEN = SOURCE.length();

 /**
  * @param args
  */
 public static void main(String[] args) {
     String result = caesarEncryption("newyork");
     System.out.println("encryption result:" + result);
     System.out.println("decryption result:" + caesarDecryption(result));

 }

 //Encryption
 public static String caesarEncryption(String s) {
     StringBuilder sb = new StringBuilder();

     if (s == null || s.length() < 1) {
         System.out.println("you Input nothing.");
         return null;
     }

     if (!isAlp(s)) {
         System.out.println("input ABC... only");
         return null;
     }

     s = s.toLowerCase();

     int len = s.length();
     for (int j = 0; j < len; j++) {
         char c = s.charAt(j);
         int a = SOURCE.indexOf(c);
         if (a == LEN -1) a = -1;
         if (a == LEN -2) a = -2;
         if (a == LEN - 3) a = -3;
         sb.append(SOURCE.charAt(a + 3));
     }
     return sb.toString();
 }

 //Decryption
 public static String caesarDecryption(String s) {
     StringBuilder sb = new StringBuilder();

     if (s == null || s.length() < 1) {
         System.out.println("you Input nothing.");
         return null;
     }

     if (!isAlp(s)) {
         System.out.println("input ABC... only");
         return null;
     }

     s = s.toLowerCase();
     for (int i = 0; i < s.length(); i++) {
         char c = s.charAt(i);
         int a = SOURCE.indexOf(c);
         if (a == 2) a = LEN + 2;
         if (a == 1) a = LEN + 1;
         if (a == 0) a = LEN;
         sb.append(SOURCE.charAt(a - 3));
     }
     return sb.toString();
 }

 public static boolean isAlp(String s) {
     String p = "^[A-Za-z]+$";
     Pattern pattern = Pattern.compile(p);
     Matcher matcher = pattern.matcher(s);
     if (matcher.find()) {
         return true;
     }
     return false;
 }
}

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 揭东县| 黔西| 宜黄县| 关岭| 达州市| 师宗县| 蒙阴县| 西畴县| 白城市| 公安县| 电白县| 河池市| 兴义市| 平遥县| 若尔盖县| 卢氏县| 佛冈县| 湖口县| 祁阳县| 文化| 昌宁县| 铜山县| 肇东市| 陆丰市| 玉门市| 柘荣县| 江门市| 沙洋县| 赤水市| 临沭县| 克什克腾旗| 屯昌县| 株洲市| 伊金霍洛旗| 应用必备| 营山县| 朝阳区| 阳曲县| 宝山区| 铜鼓县| 衢州市|