Copy Code code as follows:
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 are 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 are 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++) {
& nbsp 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;
}
}