1. 程式人生 > >字符串加密

字符串加密

can ati main scanner 操作 word 一個 turn sci

程序設計思想:

定義用來加密解密字符串的類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 }

結果截圖:

技術分享

技術分享

字符串加密