Rearrange the code so that the output shows both encoder and decoder without asking the user to
Question:
Rearrange the code so that the output shows both encoder and decoder without asking the user to choose.
Java .
The caser cipher algorithm.
(Change the switch case to for loop or while . )
Add a comment on the code to clarify it.
the code:
import java.io.*;
import java.util.*;
import java.util.Scanner;
/**
*
* @author
*/
public class Encoding_Decoding {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Scanner s = new Scanner(System.in);
String message = new String();
int key = 0 ;
String c ;
System.out.println("Enter the order of the letters");
c = s.nextLine();
System.out.println("For encryption, enter the number 1, and for decoding, enter the number 2");
int F=sc.nextInt();
switch(F){
case 1 :
System.out.print("Enter the String for Encryption:");
message = sc.next();
System.out.println("Enter Shift Key:");
key = sc.nextInt();
message = message.toLowerCase();
String cipherText = "";
for (int ii = 0; ii < message.length(); ii++) {
int charPosition = c.indexOf(message.charAt(ii));
int keyVal = (key + charPosition) % 26;
char replaceVal = c.charAt(keyVal);
cipherText += replaceVal;
}
System.out.println("Encrpyted msg:" + cipherText);
break;
case 2:
System.out.print("Enter the String for Encryption:");
message = sc.next();
System.out.println("Enter Shift Key:");
key = sc.nextInt();
cipherText = message.toLowerCase();
message = "";
for (int ii = 0; ii < cipherText.length(); ii++) {
int charPosition = c.indexOf(cipherText.charAt(ii));
int keyVal = (charPosition - key) % 26;
if (keyVal < 0) {
keyVal = c.length() + keyVal;
}
char replaceVal = c.charAt(keyVal);
message += replaceVal;
}
// System.out.println("Encrpyted msg:"+encrypt(message, key));
System.out.println("Decrypted Message:" + message);
break;
default:
System.out.println("That's not 1 or 2");
}
}
}
Systems analysis and design
ISBN: 978-0136089162
8th Edition
Authors: kenneth e. kendall, julie e. kendall