Computer Programmer
Computer Programmer

Reputation: 15

My simple caesar cipher program (java) only cycles letter forwards not backwards

I've created a program that takes the input of a message and the input of how many letters to cycle forwards or backwards. This is all works, except I can't figure out how to cycle backwards from A to Z. For example, whenever I attempt to cycle backwards from A, I get a value such as ^. I can't figure out how to cycle back to Z. This is done by converting the characters into unicode values. My code is below:

package caesarcypher;

import java.util.Scanner;

public class CaesarCypher {



    public static void main(String[] args) {


        Scanner sc=new Scanner(System.in);

        int cycle,i,n;

        String message;
        String str1="";
        String str2="";
        System.out.println("Enter the plaintext");
        message=sc.nextLine();
        message=message.toLowerCase();

        n=message.length();

        char ch1[]=message.toCharArray();
        char ch3,ch4;
        System.out.println("Enter the value by which each letter of the string is to be shifted");
        cycle=sc.nextInt();

        System.out.println();
        System.out.println("Encrypted text is");


        for(i=0;i<n;i++)
        {
            if(Character.isLetter(ch1[i]))
            {
                ch3=(char)(((int)ch1[i]+cycle-97)%26+97);
                //System.out.println(ch1[i]+" = "+ch3);
                str1=str1+ch3;
            } 
            else if(ch1[i]==' ')
            {
                str1=str1+ch1[i];
            } 
        }
        System.out.println(str1);

        System.out.println();
        System.out.println("Decrypted text is");



        char ch2[]=str1.toCharArray();
        for(i=0;i<str1.length();i++)
        {
            if(Character.isLetter(ch2[i]))
            {
                if(((int)ch2[i]-cycle)<97)
                {
                    ch4=(char)(((int)ch2[i]-cycle-97+26)%26+97);

                }
                else
                {
                    ch4=(char)(((int)ch2[i]-cycle-97)%26+97);
                }
                str2=str2+ch4;
            } 

            else if(ch2[i]==' ')
            {
                str2=str2+ch2[i];
            } 
        }
        System.out.println(str2);

    }
}

Upvotes: 1

Views: 54

Answers (1)

Thomas
Thomas

Reputation: 5094

This is because of how modulo arithmetic works.

(-1) % 26 = -1

So when you add it to 97, you're still before A. Example for cycling back by 1.

 ('A' + cycle - 97) % 26 + 97
 (97 -1 -97) % 26 + 97
 -1%26 + 97
 -1 + 97. <----- NOT +25

The simplest solution is to just add 26 to cycle if it's a negative number, though it will still break on input like -50. You appear to have already solved a similar problem in your decrypt section.

Upvotes: 3

Related Questions