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

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");
   }

}
   
}
 

Step by Step Solution

3.48 Rating (151 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

import javaio import javautil import javautilScanner This program implements the Caesar cipher algor... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!