java中输入一个密码(只能由数字或字母组成) 对密码进行加密,加密规则是每个字符向后移动5位,例如明文:"afcz194", 暗文:"fkhe649"
时间: 2023-05-15 12:06:05 浏览: 84
可以使用以下代码实现:
```java
import java.util.Scanner;
public class PasswordEncryption {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入密码:");
String password = scanner.nextLine();
String encryptedPassword = encryptPassword(password);
System.out.println("加密后的密码为:" + encryptedPassword);
}
public static String encryptPassword(String password) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (Character.isLetterOrDigit(c)) {
c += 5;
if (Character.isLetter(c) && ((Character.isUpperCase(password.charAt(i)) && c > 'Z') || (Character.isLowerCase(password.charAt(i)) && c > 'z'))) {
c -= 26;
} else if (Character.isDigit(c) && c > '9') {
c -= 10;
}
}
sb.append(c);
}
return sb.toString();
}
}
```
对于输入的密码,我们遍历每个字符,如果是字母或数字,就将其向后移动5位,如果移动后超出了字母或数字的范围,就将其减去相应的偏移量。最后将加密后的密码返回即可。
例如,对于明文"afcz194",我们将其加密后得到"fkhe649"。