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.程序结果截图;