字串加密问题

古罗马皇帝凯撒在打仗时曾经使用过以下方法加密军事情报,主要方法就是字母错位实现加密功能

           

  

一.  程序设计思想:

错位需要对每个字符进行操作,需要把字符串转换为字符数组,调用string类的toCharArray方法。然后进行错位操作时需读取一个字符,然后与数字3相加,再转换为char类型,就实现了错3位加密操作,解密则减3。在加密操作中,如果加密的是字母表最后三个,则必须实现循环操作,使用ASCII码,即X加密后是A,Y加密后是B,Z加密后是C,当读到XYZ时,加密则是减去23后转换为char类型。

二。程序流程图:

 

三,源代码

package temp;
import java.util.Scanner;
public class Tast2 {
public static char[] encrypation(String str)
{
char chararry[] = str.toCharArray();
for(int i =0; i< str.length(); i++)
{

if(str.charAt(i) >= 88 && str.charAt(i) <= 90)
{
chararry[i] = (char)(str.charAt(i) - 23);
}
else if(str.charAt(i) >= 120 && str.charAt(i) <= 122)
{
chararry[i] = (char)(str.charAt(i) - 23);
}

else
{
chararry[i]= (char) (str.charAt(i) + 3) ;
}

}
return chararry;
}
public static char[] deciphering(String str)
{
char chararry[] = str.toCharArray();
for(int i =0; i< str.length(); i++)
{

if(str.charAt(i) >= 65 && str.charAt(i) <= 67)
{
chararry[i] = (char)(str.charAt(i) + 23);
}
else if(str.charAt(i) >= 97 && str.charAt(i) <= 99)
{
chararry[i] = (char)(str.charAt(i) + 23);
}

else
{
chararry[i]= (char) (str.charAt(i) - 3) ;
}

}
return chararry;
}
public static void main(String[] args) {
Scanner imput1 = new Scanner(System.in);
Scanner imput2 = new Scanner(System.in);

System.out.println("加密字符串输入1");
System.out.println("解密字符串输入2");


int x = imput1.nextInt();
System.out.print("输入一个英文字符串:");
String string = imput2.nextLine();
if(x == 1)
{
System.out.print("加密后为:");
for(int i =0;i <string.length(); i++)
{
System.out.print(Tast2.encrypation(string)[i]);
}
}
if(x == 2)
{
System.out.print("解密后为:");
for(int i =0;i <string.length(); i++)
{
System.out.print(Tast2.deciphering(string)[i]);
}
}

imput1.close();
imput2.close();
}

}

四,结果截图:

 

posted @ 2017-10-26 16:03  月影小歪  阅读(148)  评论(0编辑  收藏  举报