ROT13 Program in JAVA
ROT 13 means ROTATE 13. It is an Encryption Scheme which works by cyclic shifting of each Lower Case and Upper Case letter 13 position.
Example :-
Input - Encryption
Output - Rapelcgvba
Input : Mind
Output : Zvaq
Algorithm and Program given below :-
Algorithm :-
Logic - Divide total alphabets into 2 halves i.e. first half is A-M and Second half is N-Z. ( Same for lower case also).
Step 1 - Input a word in a variable and find its length.
Step 2 - Extract each character and check whether it is in A-M range or N-Z range.
Step 3 - If the character is in the first half then increment the value of ASCII code by 13 by using type casting. If the character is in the second half then decrease the value of ASCII code by 13 by using type casting.
Step 4 - convert the new ASCII code into character in a new variable.
Step 5 - Store the new character in new string variable. (Say this word is Encrypted word)
Step 6 - Display both Original and Encrypted word.
Program :-
import java.io.*;
import java.util.*;
class ROT13
{
public static void main(String args[])
{
Scanner in= new Scanner(System.in);
String str,str1= ""; // string variables to store words
char ch,ch1; // character variables
int i,y,l; // 'i' for loop , 'y' to convert letter into integer
System.out.println("Enter Message");
str= in.nextLine(); // storing original word
l= str.length(); // storing length of the word
for(i=0;i<l;i++)
{
ch= str.charAt(i); // extracting character of the string
if(ch>='A'&&ch<='M'||ch>='a'&&ch<='m')
{
y=(int)ch+13;
ch=(char)y;
str1=str1+ch;
}
else if(ch>='N'&&ch<='Z'||ch>='n'&&ch<='z')
{
y=(int)ch-13;
ch=(char)y;
str1=str1+ch;
}
}
System.out.println("Original Message : " +str); // Printing Original String
System.out.println("Encrypted Message : " +str1); // Printing Encrypted String
} // End of Main
} // End of Class
Note : The program is written in the easiest way possible so try to understand it. If you face any problem in understanding this program than feel free to contact/comment.
All the Best :) Keep Learning :)
Comments