2. Java编写一个加密程序,要求从键盘输入一个字符串,然后输出加密后的字符串。加密规则是对每个字母转换为下一个字母表示,原来是a转换为b,原来是B转换为C,原来是z转换为a,原来是Z转换为A。比如:输入I like math.输出J mjlf nbui.再写出此程序的解密程序
时间: 2024-02-19 15:57:27 浏览: 173
加密程序代码:
```java
import java.util.Scanner;
public class Encrypt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要加密的字符串:");
String plaintext = scanner.nextLine();
StringBuilder ciphertext = new StringBuilder();
for (int i = 0; i < plaintext.length(); i++) {
char c = plaintext.charAt(i);
if (c >= 'a' && c < 'z' || c >= 'A' && c < 'Z') {
c++;
} else if (c == 'z') {
c = 'a';
} else if (c == 'Z') {
c = 'A';
}
ciphertext.append(c);
}
System.out.println("加密后的字符串为:" + ciphertext);
}
}
```
解密程序代码:
```java
import java.util.Scanner;
public class Decrypt {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要解密的字符串:");
String ciphertext = scanner.nextLine();
StringBuilder plaintext = new StringBuilder();
for (int i = 0; i < ciphertext.length(); i++) {
char c = ciphertext.charAt(i);
if (c > 'a' && c <= 'z' || c > 'A' && c <= 'Z') {
c--;
} else if (c == 'a') {
c = 'z';
} else if (c == 'A') {
c = 'Z';
}
plaintext.append(c);
}
System.out.println("解密后的字符串为:" + plaintext);
}
}
```
运行程序时,先运行加密程序,再用加密后的字符串作为解密程序的输入,即可得到原始字符串。
阅读全文