In Chapter 8, we learned about a simple encryption algorithm called a Caesar cip
ID: 3792925 • Letter: I
Question
Explanation / Answer
Solution:
Please find the explanation in the comments for the encryption:
Note: Use of shorthand notation for small operations helps in code-optimization and is also a decent programming practice.
CeaserCipher.java
import java.util.Scanner;
public class CeaserCipher {
public static void main(String[] args) {
int counter = 0, shift = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter the characters [Max length is 10, use "%" for deliminating your input before entering 10 characters]:");
char[] inputArray = new char[10];
while(counter < 10){
inputArray[counter] = reader.next().trim().charAt(0);
if(inputArray[counter] == '%'){
//omitting the terminator character with the default value of a char[]
inputArray[counter] = 'u0000';
break;
}
counter++;
}
System.out.println("Enter the shift:");
shift = reader.nextInt();
System.out.println("***********");
System.out.println("Befor encryption:");
for(int i = 0; i< counter; i++){
System.out.print(inputArray[i]+" ");
}
System.out.println();
//Logic for encryption : shifting the character by the designated
//shift
for(int i = 0; i< counter ; i++){
//Taking the present character as buffer
char buffer = inputArray[i];
//Shifting the buffer with specified shift
buffer+=shift;
//Checking whether the buffer is in the permissible ASCII value
//range for upper case characters or not
if(buffer > 90){
int offSet = buffer - 90;
offSet+=65;
inputArray[i] = (char)offSet;
}else{
inputArray[i] = buffer;
}
}
System.out.println("***********");
System.out.println("After encryption:");
for(int i = 0; i< counter; i++){
System.out.print(inputArray[i]+" ");
}
System.out.println();
System.out.println("***********");
}
}