对输入的字符串进行加解密,并输出

题目要求:

加密方法为: 当内容是英文字母时则用该英文字母的后一个字母替换,同时字母变换大小写,如字母a时则替换为B;字母Z时则替换为a; 当内容是数字时则把该数字加1,如0替换1,1替换2,9替换0; 其他字符不做变化。 解密方法为加密的逆过程。 数据范围:输入的两个字符串长度满足 ,保证输入的字符串都是只由大小写字母或者数字组成

代码如下:

import java.util.Scanner;

public class EncryptDecryptString {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入需要加密/解密的字符串:");
        String str = scanner.nextLine();
        System.out.println("请选择加密或解密:1.加密 2.解密");
        int choice = scanner.nextInt();
        scanner.close();
        String result = "";
        switch (choice) {
            case 1:
                result = encrypt(str);
                System.out.println("加密后的字符串为:" + result);
                break;
            case 2:
                result = decrypt(str);
                System.out.println("解密后的字符串为:" + result);
                break;
            default:
                System.out.println("无效的选择!");
                break;
        }

    }

    /**
     * 加密函数
     *
     * @param str 需要加密的字符串
     * @return 加密后的字符串
     */
    private static String encrypt(String str) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isLetter(ch)) {
                ch = shiftChar(ch);
            } else if (Character.isDigit(ch)) {
                ch = shiftDigit(ch);
            }
            result.append(ch);
        }
        return result.toString();
    }

    /**
     * 解密函数
     *
     * @param str 需要解密的字符串
     * @return 解密后的字符串
     */
    private static String decrypt(String str) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (Character.isLetter(ch)) {
                ch = shiftChar(ch);
            } else if (Character.isDigit(ch)) {
                ch = shiftDigit(ch);
            }
            result.append(ch);
        }
        return result.toString();
    }

    /**
     * 字母加密/解密函数
     *
     * @param ch 需要加密/解密的字母
     * @return 加密/解密后的字母
     */
    private static char shiftChar(char ch) {
        if (Character.isLowerCase(ch)) {
            return (char) ((ch - 'a' + 1) % 26 + 'A');
        } else {
            return (char) ((ch - 'A' + 1) % 26 + 'a');
        }
    }

    /**
     * 数字加密/解密函数
     *
     * @param ch 需要加密/解密的数字
     * @return 加密/解密后的数字
     */
    private static char shiftDigit(char ch) {
        return (char) ((ch - '0' + 1) % 10 + '0');
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值