04-課後作業1-字符串加密
阿新 • • 發佈:2017-10-27
static 錯誤 logs con left util ann ont 設計思想
1.程序設計思想:
程序首先需要獲取要加密的或者待解密字符串,然後通過算法進行字符錯位,關鍵也是字符的錯位,最後直接調用函數輸出字符串。
2.程序流程圖:
3.源程序:
import java.util.Scanner; public class Caesarcipher { public static void main(String[] args) { System.out.print("請選擇操作(1.加密、2.解密):"); Scanner sc = new Scanner(System.in); int index = sc.nextInt(); if (1 == index) { System.out.print("請輸入字符串:"); String str = sc.next(); StringBuffer newStr = new StringBuffer(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { case ‘x‘: newStr.append(‘a‘); break; case ‘y‘: newStr.append(‘b‘); break; case ‘z‘: newStr.append(‘c‘); break; default: if (!(c >= ‘a‘ && c <= ‘w‘)) { newStr.append(c); continue; } char newChar = (char) (c + 3); newStr.append(newChar); } } System.out.println("加密後的字符串是:" + newStr.toString()); } else if (2 == index) { System.out.print("請輸入字符串:"); String str = sc.next(); char[] arr = str.toCharArray(); for (int i = 0; i < arr.length; i++) { switch (arr[i]) { case ‘a‘: arr[i] = ‘x‘; break; case ‘b‘: arr[i] = ‘y‘; break; case ‘c‘: arr[i] = ‘z‘; break; default: if (!(arr[i] >= ‘d‘ && arr[i] <= ‘z‘)) { continue; } arr[i] -= 3; } } System.out.print("解密後的字符串是:"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]); } } else { System.out.println("輸入錯誤,請輸入1或2"); } sc.close(); } }
4.程序結果截圖;
04-課後作業1-字符串加密