字符串加密

 

程序设计思想:

         定义用来加密解密字符串的类Password:

                   在Password中定义一个私有成员变量int key作为字符串加密解密的偏移量。

                   同时定义设置该变量值的公有函数setKey(int y)。

                   定义加密字符串的函数encrypt(String s):

                            该函数将s中每个字符设为该字符对应ASCII码表的后key个字符,返回此串。

                   定义解密字符串的函数decode(String s):

                            该函数将s中每个字符设为该字符对应ASCII码表的前key个字符,返回此串。

         定义测试类TestPass:

                   将主函数写在此类:

                            定义一个Password对象pass,以便之后的操作。

                            提示用户首先输入一个字符串str,表示之后对该字符串进行操作。

                            显示选项菜单(加密字符串、解密字符串)。

                            用户输入选项c,以及key。

                            使用pass调用setKey,将用户输入的key赋值给pass.key。

                            判断c的值,选择调用encrypt(String s)或decode(String s)并输出结果。

                            程序结束。

程序流程图:

        

源代码:

 1 import java.util.*;
 2 class Password{
 3     private int key;
 4     public Password(){
 5         key = 0;
 6     }
 7     public void setKey(int y){
 8         key = y;
 9     }
10     public String encrypt(String s){
11         String r = "";
12         for(int i = 0;i < s.length();i++)
13             r += (char)(s.charAt(i) + 3);
14         return r;
15     }
16     public String decode(String s){
17         String r = "";
18         for(int i = 0;i < s.length();i++)
19             r += (char)(s.charAt(i) - 3);
20         return r;
21     }
22 }
23 
24 public class TestPass {
25     public static void main(String[] args){
26         Scanner in = new Scanner(System.in);
27         Password pass = new Password();
28         String str = new String();
29         System.out.println("请输入一个字符串:");
30         str = in.next();
31         
32         System.out.println("请输入要执行的操作:");
33         System.out.println("1.字符串加密");
34         System.out.println("2.字符串解密");
35         int c = 0;
36         c = in.nextInt();
37         
38         int y = 0;
39         System.out.println("请输入Key:");
40         y = in.nextInt();
41         pass.setKey(y);
42         
43         switch(c)
44         {
45         case 1:System.out.println("字符串加密后的结果为" + pass.encrypt(str));break;
46         case 2:System.out.println("字符串解密后的结果为" + pass.decode(str));break;
47         default:System.out.println("输入错误!");
48         }
49     }
50 }

结果截图:

 

posted @ 2017-10-24 21:45  ╄冷丶夜♂  阅读(670)  评论(0编辑  收藏  举报