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 char; found int
Here is my code so far:
import java.util.Scanner;
import java.io.*;
public class CaesarCipher
{
public static void main (String [] args) {
char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z'};
char[] message = "onceuponatime".toCharArray();
char[] eMessage = new char[message.length];
char shift = 3;
//encrypting message
for(int i = 0; i <= message.length; ++i)
{
eMessage[i] = (message[i] + shift) % (char) letters.length;
System.out.println(x);
}
}
}
What causes this error? How can I implement a caesar Cipher shift to increase each letter in a string by 3?
Pseudocode: Loop through each character in the string. Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26) If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
The Caesar Cipher is a type of shift cipher. Shift Ciphers work by using the modulo operator to encrypt and decrypt messages. The Shift Cipher has a key K, which is an integer from 0 to 25.
How to encrypt using Caesar cipher? Example: Crypt DCODEX with a shift of 3 . To encrypt D , take the alphabet and look 3 letters after: G . So D is encrypted with G . To encrypt X , loop the alphabet: after X : Y , after Y : Z , after Z : A . So X is coded A .
shift
spaces.Restrictions:
Pseudocode:
Function:
String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
How to invoke it:
System.out.println(cipher("abc", 3)); //prints def
System.out.println(cipher("xyz", 3)); //prints abc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With