I have to write the code for this exercise, but i couldn\'t complete it. this is
ID: 3764537 • Letter: I
Question
I have to write the code for this exercise, but i couldn't complete it.
this is what i have to do.
and here is what i did
Write a program to implement a simple Caesar cipher: each letter in the plaintext is shifted a certain number of spaces down the alphabet. Thus, the shift acts as the key to produce the ciphertext. For example, with a key of 1, 'a' would be replaced by 'b', 'b' would become 'c', 'z' would become 'a', and so on The program should take as input a file called "input" containing an integer which is the encryption key then the action to be applied (E for Encryptor D for Decrypt) and then the plaintext taht will be crypted The program should first preprocess the plaintext to remove punctuations and spaces, and convert it into a lower case since your alphabet is lower case only. (Hint: use exercise #1 above for this part)Explanation / Answer
Please check below program
import java.util.Scanner;
public class CC
{
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainText, int shiftKey)
{
plainText = plainText.toLowerCase();
String cipherText = "";
for (int i = 0; i < plainText.length(); i++)
{
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int keyVal = (shiftKey + charPosition) % 26;
char replaceVal = ALPHABET.charAt(keyVal);
cipherText += replaceVal;
}
return cipherText;
}
public static String decrypt(String cipherText, int shiftKey)
{
cipherText = cipherText.toLowerCase();
String plainText = "";
for (int i = 0; i < cipherText.length(); i++)
{
int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
int keyVal = (charPosition - shiftKey) % 26;
if (keyVal < 0)
{
keyVal = ALPHABET.length() + keyVal;
}
char replaceVal = ALPHABET.charAt(keyVal);
plainText += replaceVal;
}
return plainText;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println(“String for Encryption: ");
String message = new String(“input”);
message = sc.next();
System.out.println(encrypt(message, 1));
System.out.println(decrypt(encrypt(message, 1), 1));
sc.close();
}
}