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

后端 未结 5 1666
走了就别回头了
走了就别回头了 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:05

    The warning is due to you attempting to add an integer (int shift = 3) to a character value. You can change the data type to char if you want to avoid that.

    A char is 16 bits, an int is 32.

    char shift = 3;
    // ...
    eMessage[i] = (message[i] + shift) % (char)letters.length;
    

    As an aside, you can simplify the following:

    char[] message = {'o', 'n', 'c', 'e', 'u', 'p', 'o', 'n', 'a', 't', 'i', 'm', 'e'}; 
    

    To:

    char[] message = "onceuponatime".toCharArray();
    

提交回复
热议问题