📄 caesar.java
字号:
/*
*凯撒加密算法
*此算法中区分了字母的大小写,并可以保留标点符号
*/
public class Caesar
{
int key = 3;
public String getCipher(String message)//to encrypt
{
char msgChar [] = message.toCharArray();
int len = msgChar.length;
char cipChar [] = new char[len];
for (int i=0; i<len ;i++ )
{
cipChar[i] = convert(msgChar[i],1);
}
String cipher = new String(cipChar);
return cipher;
}
public String getMessage(String cipher)//to decode
{
char cipChar[] = cipher.toCharArray();
int len = cipChar.length;
char msgChar[] = new char[len];
for (int i=0 ; i<len ;i++ )
{
msgChar[i] = convert(cipChar[i],-1);
}
String message = new String(msgChar);
return message;
}
public char convert(char c , int op)//when op = 1 stands for encrypting , when op = -1 stands for decoding
{
int num = (int)c;
if (num>=65 && num<=90)//if it is up case
{
int res = num + key*op;
if (res > 90)//test whether the number is out of bound
res = res-26;
else if (res <65)
res = res+26;
return (char)res;
}
else if (num>=97 && num<=122)//if it is low case
{
int res = num + key*op;
if (res > 122)//test whether the number is out of bound
res = res-26;
else if (res <97)
res = res+26;
return (char)res;
}
else
{
return c;
}
}
/*
*test if correct
*/
public static void main(String [] args)
{
Caesar caesar = new Caesar();
String message = new String("For test!");
String cipher = caesar.getCipher(message);
System.out.println("The Cipher is: "+cipher);
message = caesar.getMessage(cipher);
System.out.println("The Message is: "+message);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -