04-String——课后作业1:字串加密
生活随笔
收集整理的這篇文章主要介紹了
04-String——课后作业1:字串加密
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:請編寫一個程序,加密或解密用戶輸入的英文字串要求設計思想、程序流程圖、源代碼、結果截圖。
?
?
程序設計思想:首先由用戶選擇是加密還是解密,利用String類中的charAt函數依次取出字串中的字符,如果加密(解密)就把取出的字符利用強制轉換轉換成int型之后如果是XYZ(ABC)就減(加)23其他的加(減)3然后再轉換成char類型,然后定義一個char類型數組用來儲存轉換之后的字符。
?
?
程序流程圖:這里只寫了破解時的流程圖,加密時基本一樣。
?
?
?
程序源代碼:
1 import java.util.Scanner; 2 3 public class SwitchPassword { 4 5 Scanner input = new Scanner(System.in); 6 7 //加密字串 8 public void encrypt() 9 10 { 11 12 System.out.print("請輸入要加密的字串:"); 13 14 String str = input.next(); 15 16 char encryptstr[] = new char[str.length()]; 17 18 for(int i = 0;i < str.length();i ++) 19 20 { 21 22 if(str.charAt(i) == 'X' || str.charAt(i) == 'Y' || str.charAt(i) == 'Z') 23 24 { 25 26 encryptstr[i] = (char)((int)str.charAt(i) - 23); 27 28 } 29 30 else 31 32 encryptstr[i] = (char)((int)str.charAt(i) + 3); 33 34 } 35 36 System.out.print("加密之后的字串為:"); 37 38 for(int i = 0;i < str.length();i ++) 39 40 { 41 42 System.out.print(encryptstr[i]); 43 44 } 45 46 } 47 48 //破解字串 49 public void crack() 50 51 { 52 53 System.out.print("請輸入要破解的字串:"); 54 55 String str = input.next(); 56 57 char crackstr[] = new char[str.length()]; 58 59 for(int i = 0;i < str.length();i ++) 60 61 { 62 63 if(str.charAt(i) == 'A' || str.charAt(i) == 'B' || str.charAt(i) == 'C') 64 65 { 66 67 crackstr[i] = (char)((int)str.charAt(i) + 23); 68 69 } 70 71 else 72 73 crackstr[i] = (char)((int)str.charAt(i) - 3); 74 75 } 76 77 System.out.print("破解之后的字串為:"); 78 79 for(int i = 0;i < str.length();i ++) 80 81 { 82 83 System.out.print(crackstr[i]); 84 85 } 86 87 } 88 89 public static void main(String[] args) { 90 91 Scanner input = new Scanner(System.in); 92 93 SwitchPassword s = new SwitchPassword(); 94 95 System.out.println("請選擇: 1.加密 \t2.破解"); 96 97 int ch = input.nextInt(); 98 99 switch(ch) 100 101 { 102 103 case 1: 104 105 s.encrypt();break; 106 107 case 2: 108 109 s.crack();break; 110 111 } 112 113 } 114 115 }?
?
程序運行結果:
?
轉載于:https://www.cnblogs.com/guo-xu/p/7731899.html
總結
以上是生活随笔為你收集整理的04-String——课后作业1:字串加密的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net拦截器
- 下一篇: 洛谷 P1849 [USACO12MAR