凯撒加密(key为3)

基本思想:

加密是把字符串中的每一个字符+3解密是每一个字符-3

源代码:

package demo;
import java.util.Scanner;

class Encryption{
String a;
public void encryption(String q){
String string= "";
for(int i = 0;i < q.length();i++)
{
char b=q.charAt(i);
if(b >= 'a'&&b <='z')
{
b += 3;
if(b > 'z')
b-=26;
if(b < 'a')
b=+26;
}
else if(b >= 'A'&&b <= 'Z')
{
b+=3;
if(b > 'Z')
b-=26;
if(b < 'A')
b+=26;
}
string += b;
}
System.out.println("加密后为:"+string);
}

}
class Decryption{
String a;
public void decryption(String q){
String string= "";
for(int i = 0;i < q.length();i++)
{
char b=q.charAt(i);
if(b >= 'a'&&b <='z')
{
b -= 3;
if(b > 'z')
b-=26;
if(b < 'a')
b+=26;
}
else if(b >= 'A'&&b <= 'Z')
{
b-=3;
if(b > 'Z')
b-=26;
if(b < 'A')
b+=26;
}
string += b;
}
System.out.println("解密后为:"+string);
}

}
public class Password{
public static void main(String[] args){
System.out.println("a。加密 b.解密");
Scanner choose = new Scanner(System.in);
String a = choose.nextLine();
if(a.equalsIgnoreCase("a"))
{
Scanner c = new Scanner(System.in);
System.out.println("请输入明文:");
String b = c.nextLine();
Encryption en = new Encryption();
en.encryption(b);
}
else if(a.equalsIgnoreCase("b")) // equals 用来比较两个对象所表示的字符是否相同
{ // equalsIgnoreCase 用来比较对象所代表的字符与括号中字符是否相同
Scanner c = new Scanner(System.in);
System.out.println("请输入密码:");
String b = c.nextLine();
Decryption de = new Decryption();
de.decryption(b);
}
}
}

结果截图:

posted @ 2015-10-21 18:02  ChanGeZ  阅读(717)  评论(0编辑  收藏  举报