Caesar Cipher Code : The code is not letting me input any sentences or strings with spaces even when i am using sc.nextLine(), neither is it giving an error. JUST BLANK.
import java.util.*;
public class CaesarCipher
{
protected char[] encoder = new char[26];
protected char[] decoder = new char[26];
/** Constructor that initializes the encryption and decryption arrays */
public CaesarCipher(int rotation)
{
for(int k=0;k<26;k++)
{
encoder[k] = (char)('A' + (k + rotation)%26);
decoder[k] = (char)('A' + (k - rotation+26)%26);
}
}
/** Returns String representing encrypted message. */
public String encrypt(String message)
{
return transform(message,encoder);
}
public String decrypt(String Secret)
{
return transform(Secret, decoder);
}
public String transform(String Original,char[] code)
{
char msg[] = Original.toCharArray();
for(int k=0;k<msg.length;k++)
{
if(Character.isUpperCase(msg[k]))
{
int j = msg[k] - 'A';
msg[k] = code[j];
}
}
return new String(msg);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number between 1 and 26 : ");
int r = sc.nextInt();
System.out.println();
CaesarCipher cipher = new CaesarCipher(r);
System.out.println("Encryption code : " + new String(cipher.encoder));
System.out.println("Decryption code : " + new String(cipher.decoder));
System.out.println();
System.out.println("Enter a Message to Encrypt : ");
String message = sc.nextLine();
String coded = cipher.encrypt(message.toUpperCase());
System.out.println("Encrypted Message : " + coded);
System.out.println();
System.out.println("Decrypted Message : " + cipher.decrypt(coded));
sc.close();
}
}
Output :
Enter any number between 1 and 26 : 4
Encryption code : EFGHIJKLMNOPQRSTUVWXYZABCD Decryption code : WXYZABCDEFGHIJKLMNOPQRSTUV
Enter a Message to Encrypt : Encrypted Message :
Decrypted Message :