I have a problem with caesar cipher in Java with ACM. Here's my code:
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;
}
}
When I compile I have these errors:
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
You can't add an
int
to achar
in Java without explicitly stating your consent to the possible loss of precision (overflow/underflow). Add a(char)
cast to each place anint
is used with achar
.