複製程式碼如下:
公共課凱撒{
公共靜態最終字串來源=“abcdefghijklmnopqrstuvwxyz”;
公共靜態最終 int LEN = SOURCE.length();
/**
* @參數參數
*/
公共靜態無效主(字串[] args){
字串結果 = caesarEncryption("newyork");
System.out.println("加密結果:" + result);
System.out.println("解密結果:" + caesarDecryption(result));
}
//加密
公共靜態字串凱撒加密(字串s){
StringBuilder sb = new StringBuilder();
if (s == null || s.length() < 1) {
System.out.println("你什麼也沒輸入。");
返回空值;
}
if (!isAlp(s)) {
System.out.println("僅輸入ABC...");
返回空值;
}
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));
}
返回 sb.toString();
}
//解密
公共靜態字串凱撒解密(字串s){
StringBuilder sb = new StringBuilder();
if (s == null || s.length() < 1) {
System.out.println("你什麼也沒輸入。");
返回空值;
}
if (!isAlp(s)) {
System.out.println("僅輸入ABC...");
返回空值;
}
s = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int a = SOURCE.indexOf(c);
如果 (a == 2) a = LEN + 2;
如果 (a == 1) a = LEN + 1;
如果 (a == 0) a = LEN;
sb.append(SOURCE.charAt(a - 3));
}
返回 sb.toString();
}
公共靜態布林 isAlp(String s) {
字串 p = "^[A-Za-z]+$";
模式模式 = Pattern.compile(p);
匹配器 matcher =pattern.matcher(s);
if (matcher.find()) {
返回真;
}
返回假;
}
}