凯撒密码的实现 [英] Implementation of the Caesar cipher

查看:72
本文介绍了凯撒密码的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在 Functionality.java 类中实现一个名为 encodeCaesar 的静态公共方法,该方法使用Caesar加密对文本进行编码,并且我是Java的完全新手.

I have to Implement a static public method named encodeCaesar in the class Functionality.java, which encodes a text using Caesar encryption and I am a complete novice in Java.

签名: encodeCaesar(String s,int val):字符串

该方法获取一个字符串值和一个整数值作为输入参数.字符串值中的字母(字符)将移位整数值.为简单起见,我可以假设只有字母,没有空格,数字或特殊字符.

The method gets a string value and an integer value as input parameters. The letters (characters) from the string value are to be shifted by the integer value. For simplicity, I can assume that there are only letters and no spaces, numbers or special characters.

在执行加密之前,应将字符串值转换为小写.该方法应返回一个字符串,其中每个字母均已根据指定的整数值移动.

The string value should be converted to lower case before the encryption is performed. The method should return a string where each letter has been moved according to the specified integer value.

示例: encodeCaesar("Ac",3)返回"df" .如果给定的整数值小于0或大于26,则应返回一个空字符串.

Example: encodeCaesar("Ac",3) returns "df". If the given integer value is less than 0 or greater than 26, an empty string should be returned.

public class Functionality {
    public static void main(String[] args) {
    }

    public static String encodeCaesar(String s, int val) {
        char[] newString = s.toCharArray();
        for (int i = 0; i < s.length(); i++) {
            int newChar = newString[i] + val + 26;

            // Handle uppercase letters
            while (Character.isUpperCase(newString[i]) && newChar >= 65 + 26) {
                newChar -= 26;
            }

            // Handle lowecase letters
            while (Character.isLowerCase(newString[i]) && newChar >= 97 + 26) {
                newChar -= 26;
            }

            newString[i] = (char) (newChar);
        }

        return String.valueOf(newString);
    }
}

我的问题是,作为回报,它只会给我真或假.我该如何解决:该方法应返回一个字符串,其中每个字符已根据指定的整数值移动.

My problem is that in return it give me only true or false. How can I solve this: The method should return a string where each character has been moved according to the specified integer value.

推荐答案

public static String caesar(String s, int val) {
    char[] newString = s.toLowerCase().toCharArray();
    for (int i = 0; i < s.length(); i++) {
        int newChar = newString[i] + val + 26;
        // Handle lowercase letters
        while (Character.isLowerCase(newString[i]) && newChar >= 97 + 26) {
            newChar -= 26;
        }
        newString[i] = (char) (newChar);
    }
    return String.valueOf(newString);
}

我解决了这个问题.

这篇关于凯撒密码的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆