题解 | #字符串加解密#简单明了解法,分享给大家

字符串加解密

https://www.nowcoder.com/practice/2aa32b378a024755a3f251e75cbf233a

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String a = in.nextLine();   //需要加密的密码
            String b = in.nextLine();   //需要解密的密码

            char[] at = a.toCharArray();
            char[] bt = b.toCharArray();
            for (int i = 0; i < at.length; i++) {
                if ((at[i] >= 'a' && at[i] <= 'z') || (at[i] >= 'A' &&
                                                       at[i] <= 'Z')) {
                    at[i] = isZandJM(at[i]);
                } else if (at[i] >= '0' && at[i] <= '9') {
                    at[i] = isNandJM(at[i]);
                } else {
                    continue;
                }
            }

            for (int i = 0; i < bt.length; i++) {
                if ((bt[i] >= 'a' && bt[i] <= 'z') || (bt[i] >= 'A' &&
                                                       bt[i] <= 'Z')) {
                    bt[i] = isZandGM(bt[i]);
                } else if (bt[i] >= '0' && bt[i] <= '9') {
                    bt[i] = isNandGM(bt[i]);
                } else {
                    continue;
                }
            }

            System.out.println(String.valueOf(at));
            System.out.println(String.valueOf(bt));
        }
    }

    private static char isZandJM(char a) {

        if (a >= 'a' && a <= 'z') {
            if (a == 'z') {
                return 'A';
            } else {
                return (char)(a - 31);
            }
        }
        if (a >= 'A' && a <= 'Z') {
            if (a == 'Z') {
                return 'a';
            }
        }
        return (char)(a + 33);
    }

    private static char isZandGM(char a) {
        if (a >= 'a' && a <= 'z') {
            if (a == 'a') {
                return 'Z';
            } else {
                return (char)(a - 33);
            }
        }
        if (a >= 'A' && a <= 'Z') {
            if (a == 'A') {
                return 'z';
            }
        }
        return (char)(a + 31);
    }

    private static char isNandJM(char a) {
        if (a == '9') {
            return '0';
        }
        return (char)(a + 1);
    }

    private static char isNandGM(char a) {
        if (a == '0') {
            return '9';
        }
        return (char)(a - 1);
    }
}

全部评论

相关推荐

11-04 14:10
东南大学 Java
_可乐多加冰_:去市公司包卖卡的
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务