题目:对输入的字符串进行加密,并输出。 加密方法为: 当内容是英文字母时则用该英文字母的后一个字母替换,同时字母变换大小写,如字母a时则替换为B;字母Z时则替换为a; 当内容是数字时则把该数字加1,如1替换0,2替换1,0替换9; 其他字符不做变化。 长度n满足:1≤n≤1000 输入: abcdefg1234 输出: BCDEFGH2345
public class Demo6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String a = in.nextLine();
System.out.println(encrypt(a));
}
}
public static String encrypt(String input) {
StringBuilder encrypted = new StringBuilder();
for (char c : input.toCharArray()) {
if (Character.isLetter(c)) {
char shifted = shiftLetter(c);
encrypted.append(shifted);
} else if (Character.isDigit(c)) {
char incremented = incrementDigit(c);
encrypted.append(incremented);
} else {
encrypted.append(c); // 其他字符不变
}
}
return encrypted.toString();
}
private static char shiftLetter(char c) {
if (Character.isLowerCase(c)) { // 之前我们讲过的一道题里边,判断是否大写字母或小写字母,用这个更简单
c = (char) ((c - 'a' + 1) % 26 + 'A');
} else if (Character.isUpperCase(c)) {
c = (char) ((c - 'A' + 1) % 26 + 'a');
}
return c;
}
private static char incrementDigit(char c) {
return (char) ((c - '0' + 1) % 10 + '0');
}
}
如果大家需要视频版本的讲解,欢迎关注我的B站: