please use basic java code. and comment ur code please. thanks Programming assig
ID: 3697694 • Letter: P
Question
please use basic java code. and comment ur code please. thanks
Programming assignment Caesar Shift 5 points. You are going to build a program that encodes messages using a simple Caesar Shift algorithm. The user will type in a message to be encoded, and your program will output an encrypted version of the users input. What is a Caesar Shift you might ask? Basically we are shifting the letters such that: original letter XYZABCDEFGHIJKLMNIPQURSUVW Encoded letter ABCDEFGHIJKLMNOPQRSTUVWXYZ IE the letter 'C' in the original message is printed as the letter 'F* in the encoded message {Three characters over) In order to do this, you need to understand a bit of how letters are encoded. If a Char represents a single letter, you can get a numerical value for that letter by saying char original = 'H'; int letterValue = original; For the letter 'H' the numeric value is 72. The values for A thru Z are 65 thru 90. Here is some psudo code. Input the user's string - convert it to upper case - examine each character in the string one at a time. If the character is a letter (ie 65 to 90) subtract three from the value. If the resulting value is less than 65, add 26 to it convert the value to a char, and add it to the encoded string Print the resultant encoded string you created.Explanation / Answer
//include package
package com.sanfoundry.setandstring;
import java.util.Scanner;
public class Caesar_shift
{
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainText, int shiftKey)
{
// check lower case alphabet
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;
}
// decrpt funcion
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;
}
//main class
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String for Encryption: ");
String message = new String();
message = sc.next();
System.out.println(encrypt(message, 3));
System.out.println(decrypt(encrypt(message, 3), 3));
sc.close();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.