Caesar cipher in Java ACM

1.8k views Asked by At

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
2

There are 2 answers

0
Marko Topolnik On BEST ANSWER

You can't add an int to a char in Java without explicitly stating your consent to the possible loss of precision (overflow/underflow). Add a (char) cast to each place an int is used with a char.

0
peter.petrov On

Here is the fixed version of your code.
Compare it with your version to make sure
you understand the changes.

    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;
     }

OUTPUT:

fgh
cde
bcd