import java.util.Scanner;/**
* @author zh.zhang
*/publicclassCaesar{/**
* Encrypt text by shifting every Latin char by add number shift for ASCII Example : A + 1 -> B
*
* @param message
* @param shift
* @return Encrypted message
*/publicstatic String encode(String message,int shift){
String encoded ="";
shift %=26;finalint length = message.length();for(int i =0; i < length; i++){// int current = message.charAt(i); //using char to shift characters because ascii// is in-order latin alphabet// Java law : char + int = charchar current = message.charAt(i);if(IsCapitalLatinLetter(current)){
current += shift;// 26 = number of latin letters
encoded +=(char)(current >'Z'? current -26: current);}elseif(IsSmallLatinLetter(current)){
current += shift;// 26 = number of latin letters
encoded +=(char)(current >'z'? current -26: current);}else{
encoded += current;}}return encoded;}/**
* Decrypt message by shifting back every Latin char to previous the ASCII Example : B - 1 -> A
*
* @param encryptedMessage
* @param shift
* @return message
*/publicstatic String decode(String encryptedMessage,int shift){
String decoded ="";
shift %=26;finalint length = encryptedMessage.length();for(int i =0; i < length; i++){char current = encryptedMessage.charAt(i);if(IsCapitalLatinLetter(current)){
current -= shift;// 26 = number of latin letters
decoded +=(char)(current <'A'? current +26: current);}elseif(IsSmallLatinLetter(current)){
current -= shift;// 26 = number of latin letters
decoded +=(char)(current <'a'? current +26: current);}else{
decoded += current;}}return decoded;}/**
* @param c
* @return true if character is capital Latin letter or false for others
*/privatestaticbooleanIsCapitalLatinLetter(char c){return c >='A'&& c <='Z';}/**
* @param c
* @return true if character is small Latin letter or false for others
*/privatestaticbooleanIsSmallLatinLetter(char c){return c >='a'&& c <='z';}publicstaticvoidmain(String[] args){
Scanner input =newScanner(System.in);
System.out.println("Please enter the message (Latin Alphabet)");
String message = input.nextLine();
System.out.println(message);
System.out.println("Please enter the shift number");int shift = input.nextInt()%26;
System.out.println("(E)ncode or (D)ecode ?");char choice = input.next().charAt(0);switch(choice){case'E':case'e':// send our function to handle
System.out.println("ENCODED MESSAGE IS \n"+encode(message, shift));break;case'D':case'd':
System.out.println("DECODED MESSAGE IS \n"+decode(message, shift));default:
System.out.println("default case");}
input.close();}}
java实现caesar加解密算法java实现caesar加解密算法这是一种替换密码,其中每个字母 在纯文本中被一个字母替换为字母表中某个固定位置的字母。import java.util.Scanner;/** * @author zh.zhang */public class Caesar { /** * Encrypt text by shifting every Latin char by add number shift for ASCII Example : A +