1. 程式人生 > >課後作業04-1

課後作業04-1

字符 src inpu scanner while pan out else cnblogs

字串加密

程序設計思想:用戶輸入1或2選擇加密還是解密,然後輸入字符串,調用加密或解密函數。加密函數:提取字符串的每個字符保存到字符變量c中令c=c-‘A‘,使字符轉換成0-25的數字,令c=(c+3)%26+‘A’,對字符進行加密,然後逐個輸出加密後的字符。解密函數:與加密函數相似,只是將c=(c+3)%26+‘A‘變為c=(c-3+23)%26+‘A‘。

程序流程圖:

技術分享

源代碼:

 1 import java.util.Scanner;
 2 
 3 public class JiaMi 
 4 
 5 {
 6     public static void main(String [] args)
7 8 { 9 String str; 10 11 int n; 12 13 Scanner input=new Scanner(System.in); 14 15 Scanner in=new Scanner(System.in); 16 17 while(true) 18 19 { 20 System.out.println("1.加密\n2.解密\n請選擇:");
21 22 n=input.nextInt(); 23 24 if(n==1) 25 26 { 27 28 System.out.println("請輸入要加密的字符串:"); 29 30 str=in.nextLine(); 31 32 jiaMi(str); 33 }
34 35 else if(n==2) 36 37 { 38 System.out.println("請輸入要解密的字符串:"); 39 40 str=in.nextLine(); 41 42 jieMi(str); 43 } 44 45 else 46 47 System.out.println("選擇錯誤"); 48 49 System.out.println(); 50 51 } 52 } 53 54 55 static void jiaMi(String p) 56 57 { 58 int c; 59 60 for(int i=0;i<p.length();i++) 61 62 { 63 c=p.charAt(i)-‘A‘; 64 65 c=(c+3)%26+‘A‘; 66 67 System.out.print((char)c); 68 69 } 70 } 71 72 static void jieMi(String p) 73 74 { 75 int c; 76 77 for(int i=0;i<p.length();i++) 78 79 { 80 c=p.charAt(i)-‘A‘; 81 82 c=(c-3+26)%26+‘A‘; 83 84 System.out.print((char)c); 85 } 86 } 87 }

結果截圖:

技術分享

技術分享

課後作業04-1