Shubam Singh Jamwal
Shubam Singh Jamwal

Reputation: 13

Trying to implement a caesar cipher in java

I am trying to implement a caesar cipher encryption in java, but I am getting wrong output if a rotation has to be done i.e for example key=2 and text is "zz" the output should be "bb". I don't know where I am wrong in the code below.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();// length of the string
        String s = in.next();// The string to be encrypted using caesar cipher
        int k = in.nextInt();// The key k
        int key;
        for(int i =0;i<n;i++){
            int ascii = (int)s.charAt(i);
            if(s.charAt(i)=='-'){
                System.out.print('-');
                continue;
            }
            if(ascii >= 65 && ascii <=90){
                if(k+ascii > 90){
                    k=k%26;
                    if(k==0){
                        k+=1;
                    }

                    ascii=64+k;
                }
                else{
                    ascii=ascii+k;
                }
            }
            if(ascii >= 97 && ascii <=122){
                if(k+ascii > 122){
                    k=k%26;
                     if(k==0){
                        k+=1;
                    }

                    ascii=96+k;
                }
                else{
                    ascii=ascii+k;
                }
            }
            char c=(char)ascii;
            System.out.print(c);
        }
    }
}

Upvotes: 0

Views: 387

Answers (2)

Orin
Orin

Reputation: 930

               if(ascii >= 65 && ascii <=90){
                    k%=26;
                    if(k+ascii > 90){
                        ascii = (ascii + k - 90)+64; //This is what it should be
                    }
                    else{
                        ascii=ascii+k;
                    }
                }
                if(ascii >= 97 && ascii <=122){
                    k%=26;
                    if(k+ascii > 122){
                        ascii = (ascii + k - 122)+96; //This is what it should be
                    }
                    else{
                        ascii=ascii+k;
                    }
                }

I narrowed it down to whenever it goes off the end, it was not wrapping around correctly. Give this a shot and it should work, at least for what I was trying.

Also, after you get input for k using in.nextInt(), I would just check if it is above 26 right there and mod it. It won't affect the answer at all and in my opinion is just cleaner.

int k = in.nextInt();
if(k > 26)
   k%=26;

Upvotes: 0

Mureinik
Mureinik

Reputation: 312219

Your modulo calculation is wrong. It should be:

k = k % 26; // not 26%k as you currently have

Or, more elegantly:

k %= 26;

Upvotes: 2

Related Questions