我正在尝试在java中实现caesar密码加密,但是如果必须进行轮换,我输出错误,例如key = 2而text是“zz”,输出应该是“bb”。我不知道下面的代码我错在哪里。
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();// length of the string
String s = in.next();// The string to be encrypted using caesar cipher
int k = in.nextInt();// The key k
int key;
for(int i =0;i<n;i++){
int ascii = (int)s.charAt(i);
if(s.charAt(i)=='-'){
System.out.print('-');
continue;
}
if(ascii >= 65 && ascii <=90){
if(k+ascii > 90){
k=k%26;
if(k==0){
k+=1;
}
ascii=64+k;
}
else{
ascii=ascii+k;
}
}
if(ascii >= 97 && ascii <=122){
if(k+ascii > 122){
k=k%26;
if(k==0){
k+=1;
}
ascii=96+k;
}
else{
ascii=ascii+k;
}
}
char c=(char)ascii;
System.out.print(c);
}
}
}
答案 0 :(得分:3)
您的模数计算错误。它应该是:
k = k % 26; // not 26%k as you currently have
或者,更优雅:
k %= 26;
答案 1 :(得分:0)
if(ascii >= 65 && ascii <=90){
k%=26;
if(k+ascii > 90){
ascii = (ascii + k - 90)+64; //This is what it should be
}
else{
ascii=ascii+k;
}
}
if(ascii >= 97 && ascii <=122){
k%=26;
if(k+ascii > 122){
ascii = (ascii + k - 122)+96; //This is what it should be
}
else{
ascii=ascii+k;
}
}
我把它缩小到最后,它没有正确缠绕。给它一个镜头它应该工作,至少我正在尝试。
此外,在使用in.nextInt()获取k的输入后,我只是检查它是否在26以上并修改它。它根本不会影响答案,我认为它更干净。
int k = in.nextInt();
if(k > 26)
k%=26;