使用java 从键盘输入一段文字,采用循环移位法(例如将 a->c,b->d,>b)进行加密后输出,然后再还原为原内容输
时间: 2024-03-07 21:50:02 浏览: 15
好的,以下是使用 Java 实现循环移位加密和解密的代码示例:
```java
import java.util.Scanner;
public class CaesarCipher {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要加密的文本:");
String text = scanner.nextLine();
System.out.print("请输入移位数:");
int shift = scanner.nextInt();
String encryptedText = encrypt(text, shift);
System.out.println("加密后的文本为:" + encryptedText);
String decryptedText = decrypt(encryptedText, shift);
System.out.println("解密后的文本为:" + decryptedText);
scanner.close();
}
public static String encrypt(String text, int shift) {
// 定义加密函数
StringBuilder result = new StringBuilder();
for (char c : text.toCharArray()) {
// 对于每个字符进行循环移位加密
if (Character.isLetter(c)) {
// 只对字母进行加密
int asciiCode = (int) c + shift;
if (Character.isLowerCase(c)) {
// 对小写字母进行处理
if (asciiCode > (int) 'z') {
asciiCode -= 26;
} else if (asciiCode < (int) 'a') {
asciiCode += 26;
}
} else {
// 对大写字母进行处理
if (asciiCode > (int) 'Z') {
asciiCode -= 26;
} else if (asciiCode < (int) 'A') {
asciiCode += 26;
}
}
result.append((char) asciiCode);
} else {
// 对于非字母字符直接拼接
result.append(c);
}
}
return result.toString();
}
public static String decrypt(String text, int shift) {
// 定义解密函数
return encrypt(text, -shift);
}
}
```
这段代码中,我们定义了 `encrypt` 和 `decrypt` 两个函数,分别用于加密和解密。其中,加密函数通过循环移位的方式对每个字母进行加密,而解密函数则是通过反向移位的方式进行解密。在加密和解密的过程中,我们需要注意字母的大小写和循环移位的边界问题。
希望这个代码示例能够帮助你解决问题。如果还有其他问题,可以继续提问。