我在使用ACM的Java中遇到了caesar密码的问题。这是我的代码:
import acm.program.*;
public class Ceasar extends ConsoleProgram{
public void run() {
println("This program encodes a
message using a Caesar cipher.");
int shifter=readInt("Enter the number of character positions to shift: ");
String msg=readLine("Enter a message :");
String Solution=encodeCaesarCipher(msg,shifter);
println("Encoded message: "+Solution);
}
private String encodeCaesarCipher(String str,int shift){
String result="";
for (int i=0;i<str.length();i++){
char helper=str.charAt(i);
helper=(helper+shift);
if (helper>'Z'||helper>'z') helper =(helper-26);
if (helper<'A'||helper<'a') helper=(helper+26);
result= result+helper;
}
return result;
}
}
编译时我遇到这些错误:
Ceasar.java:21: error: possible loss of precision
helper=helper+shift;
^
required: char
found: int
Ceasar.java:22: error: possible loss of precision
if (helper>'Z'||helper>'z') helper =helper-26;
^
required: char
found: int
Ceasar.java:23: error: possible loss of precision
if (helper<'A'||helper<'a') helper=helper+26;
^
required: char
found: int
3 errors
答案 0 :(得分:3)
如果没有明确表示您同意可能的精度损失(溢出/下溢),则无法在Java中向int
添加char
。添加(char)
广告代码,int
与char
一起使用{/ 1}}。
答案 1 :(得分:1)
以下是您的代码的固定版本
将其与您的版本进行比较以确保
你理解这些变化。
public static void main(String[] args){
String s = encodeCaesarCipher("abc", 5);
System.out.println(s);
s = encodeCaesarCipher("abc", 2);
System.out.println(s);
s = encodeCaesarCipher("abc", 1);
System.out.println(s);
}
private static String encodeCaesarCipher(String str,int shift){
String result="";
for (int i=0;i<str.length();i++){
int helper=str.charAt(i);
helper=(helper+shift);
if (helper>'Z'||helper>'z') helper =(helper-26);
if (helper<'A'||helper<'a') helper=(helper+26);
result= result+ (char)helper;
}
return result;
}
输出:
fgh
cde
bcd