Java, How to implement a Shift Cipher (Caesar Cipher)

后端 未结 5 1662
走了就别回头了
走了就别回头了 2020-11-27 20:26

I want to implement a Caesar Cipher shift to increase each letter in a string by 3.

I am receiving this error:

possible loss of precision required         


        
5条回答
  •  無奈伤痛
    2020-11-27 21:15

    Below code handles upper and lower cases as well and leaves other character as it is.

    import java.util.Scanner;
    
    public class CaesarCipher
    {
        public static void main(String[] args)
        {
        Scanner in = new Scanner(System.in);
        int length = Integer.parseInt(in.nextLine());
        String str = in.nextLine();
        int k = Integer.parseInt(in.nextLine());
    
        k = k % 26;
    
        System.out.println(encrypt(str, length, k));
    
        in.close();
        }
    
        private static String encrypt(String str, int length, int shift)
        {
        StringBuilder strBuilder = new StringBuilder();
        char c;
        for (int i = 0; i < length; i++)
        {
            c = str.charAt(i);
            // if c is letter ONLY then shift them, else directly add it
            if (Character.isLetter(c))
            {
            c = (char) (str.charAt(i) + shift);
            // System.out.println(c);
    
            // checking case or range check is important, just if (c > 'z'
            // || c > 'Z')
            // will not work
            if ((Character.isLowerCase(str.charAt(i)) && c > 'z')
                || (Character.isUpperCase(str.charAt(i)) && c > 'Z'))
    
                c = (char) (str.charAt(i) - (26 - shift));
            }
            strBuilder.append(c);
        }
        return strBuilder.toString();
        }
    }
    

提交回复
热议问题