用java编写一个凯撒密码程序,实现将一个明文加密
时间: 2024-05-14 08:17:04 浏览: 11
好的,以下是用 Java 编写的凯撒密码程序的示例代码:
```
import java.util.Scanner;
public class CaesarCipher {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入明文:");
String plainText = sc.nextLine();
System.out.print("请输入偏移量:");
int offset = sc.nextInt();
String cipherText = encrypt(plainText, offset);
System.out.println("密文是:" + cipherText);
}
public static String encrypt(String plainText, int offset) {
char[] chars = plainText.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c >= 'A' && c <= 'Z') {
chars[i] = (char) ((c - 'A' + offset) % 26 + 'A');
} else if (c >= 'a' && c <= 'z') {
chars[i] = (char) ((c - 'a' + offset) % 26 + 'a');
}
}
return new String(chars);
}
}
```
运行程序后,输入明文和偏移量,程序就会输出加密后的密文。例如,输入明文为 `hello world`,偏移量为 3,则程序输出的密文为 `khoor zruog`。
以上是一个简单的凯撒密码实现,方便起见,我们只考虑了字母的大小写,没有考虑其他字符。在实际的应用中,还需要考虑更多的因素来提高密码的安全性。