我在使用 ACM 的 Java 中使用凯撒密码时遇到问题。这是我的代码:
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
最佳答案
您不能在 Java 中将 int
添加到 char
中,除非明确声明您同意可能的精度损失(溢出/下溢)。在 int
与 char
一起使用的每个地方添加一个 (char)
转换。
关于java - Java ACM 中的凯撒密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20829305/