Java Programming

 Create a Java Class with two methods ,

1) encrypt : which will take string and shift number as argument and return the encrypted string using Caesar Cipher technique. 
For Example: 
example-1 input: "abc" with shift number to be 2 output: "cde" 
example-2 input: "arjun" with shift number to be 1 output: "bskvo" 

2) decrypt : which will take string and shift number as argument and return decrypted string using Caesar Cipher technique. 
For Example: 
example-1 input: "cde" with shift number to be 2 output: "abc" 
example-2 input: "bskvo" with shift number to be 1 output: "arjun"


import java.util.*;

class CaesarCipher {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter message: ");

String str = sc.nextLine();

System.out.print("Enter shift number: ");

int num = sc.nextInt();

encrypt(str, num);

decrypt(str, num);

encrypt("abc", 2);

decrypt("bskvo", 1);

}

static void encrypt(String str, int num) {

char[] arr = new char[str.length()];

for(int i=0; i<str.length(); i++) {

int ascii = (int) str.charAt(i);

if((ascii>64 && (ascii+num)<91) || (ascii>96 && (ascii+num)<123))

ascii += num;

else {

int temp = num;

while(ascii != 122 && ascii != 90) {

ascii += 1;

temp -= 1;

}

if(ascii == 90)

ascii = 64 + temp;

else

ascii = 96 + temp;

}

arr[i] = (char) ascii;

}

System.out.print("Encrypt: ");

System.out.println(arr);

}

static void decrypt(String str, int num) {

char[] arr = new char[str.length()];

for(int i=0; i<str.length(); i++) {

int ascii = (int) str.charAt(i);

if(((ascii-num)>64 && ascii<91) || ((ascii-num)>96 && ascii<123))

ascii -= num;

else {

int temp = num;

while(ascii != 97 && ascii != 65) {

ascii -= 1;

temp -= 1;

}

if(ascii == 65)

ascii = 91 - temp;

else

ascii = 123 - temp;

}

arr[i] = (char) ascii;

}

System.out.print("Decrypt: ");

System.out.println(arr);

}

}

Post a Comment

0 Comments