Java Caesar密码大小写环绕
我有一个问题,关于用我的凯撒密码程序包装字母表 该程序适用于所有小写字母。完美环绕,能够应用正、负移位。当我尝试输入大写字母时,大写字母不会环绕 这是我的密码:Java Caesar密码大小写环绕,java,Java,我有一个问题,关于用我的凯撒密码程序包装字母表 该程序适用于所有小写字母。完美环绕,能够应用正、负移位。当我尝试输入大写字母时,大写字母不会环绕 这是我的密码: public static StringBuilder encode(String str, int numShift) { numShift = numShift % 26; //assign each character of the string to a position in the character a
public static StringBuilder encode(String str, int numShift)
{
numShift = numShift % 26;
//assign each character of the string to a position in the character array
char[] strChars = str.toCharArray();
for (int i = 0; i < strChars.length; i++)
{
//ignore and continue if the character is not within the alphabet
if((strChars[i] < 'a' || strChars[i] > 'z') && (strChars[i]<'A' || strChars[i] > 'Z'))
continue;
//apply the shift to each character
strChars[i] += numShift;
//wrap around if the shift is beyond Z
**if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}**
}
StringBuilder encodedStr = new StringBuilder();
encodedStr.append(strChars);
return encodedStr;
}
public static void init(){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the string that you would like to encode:");
String str = scan.nextLine();
System.out.println("Please enter the number of letters you would like to shift:");
int strShift = scan.nextInt();
scan.close();
StringBuilder result = encode(str, strShift);
System.out.println(result);
}
public static void main(String[] args)
{
init();
}
让我们为单个字符实现一个环绕函数。这将由另一种方法使用。当你明智地将任务和子任务分开时,你会发现你的问题变得更容易解决。在这里,我的解决方案基于这样一个事实,即
char
变量被表示为数字,我们知道字母的数量,我们可以使用这个数字作为模类,以确保代数对我们有帮助
private static char wrapChar(char input, int amount) {
//assume for now that we have an upper-case letter
char start = 'A';
//if the assumption is mistaken...
if (('a' <= input) && (input <= 'z')) {
//then, if it is lower-case, then use lower-case
start = 'a';
} else if (!(('A' <= input) && (input <= 'Z'))) {
//target is not letter
return input;
}
//Calculate total offset compared to the first letter of the alphabet
//be it lower or upper
int offset = ((input - start) + amount) % 26;
//If offset happens to be negative, then shift a modulo period of 26
//To get the correct positive offset
if (offset < 26) {
offset += 26;
}
//Add the final offset to start and convert it to char
return ((char)(start + offset));
}
你只需要:
strChars[i] = wrapChar(strChars[i], numShift);
您的方法无法按现状工作,因为+7或更大的移位将使一些大写字母移到小写字母的范围内。我建议在转换前检查字母是否在大写范围内。如果是,请将结果转换为小写、转换并转换回。否则,就像你已经做的那样转变。这是有道理的,谢谢你,约翰!
//apply the shift to each character
strChars[i] += numShift;
//wrap around if the shift is beyond Z
**if(strChars[i] > 'z')
{
strChars[i] -= 'z';
strChars[i] += ('a' - 1);
}**
strChars[i] = wrapChar(strChars[i], numShift);