Friday 25 October 2013

Encryption

/*Encryption is a technique of coding messages to maintain their secrecy. A String array of size 'n' where 'n' is greater than 1 and less than 10, stores single sentences (each sentence ends with a full stop) in each row of the array.
Write a program to accept the size of the array.
Display an appropriate message if the size is not satisfying the given condition.
Define a string array of the inputted size and fill it with sentences row-wise.
Change the sentence of the odd rows with an encryption of two characters ahead of the original character. Also change the sentence of the even rows by storing the sentence in reverse order.
Display the encrypted sentences as per the sample data given below.
Test your program on the sample data and some random data.
Input: n=4
IT IS CLOUDY. IT MAY RAIN. THE WEATHER IS FINE. IT IS COOL.
Output: KV KU ENQWFA. RAIN MAY IT. VJG YGCVJGT KU HKPG. COOL IS IT.
Input: n=13
Output: INVALID ENTRY
*/
import java.io.*;
class Encryption
{
String a[];int n=0;
void enter()throws IOException
{
BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number greater than 1 and less than 10");
int n=Integer.parseInt(x.readLine());
if(n<1||n>10)
{
System.out.println("Invalid entry");
return;
}
a=new String[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter a sentence");
String p=x.readLine();
a[i]=p.toUpperCase();
}
}
String Encryption_by_two(String s)
{
s=s.trim();String w="";char e='\u0000';
for(int i=0;i<s.length();i++)
{
char b=s.charAt(i);
if(b=='Y')
e='A';
else if(b=='Z')
e='B';
else if(b==' ')
e=' ';
else
e=(char)(b+2);
w=w+e;
}
return w;
}
String reverse(String s)
{
s=s.trim();s=s+" ";int ipos=0;
String ns="",w="";
do
{
w=s.substring(ipos,s.indexOf(' '));
ns=w+" "+ns;
s=s.substring(s.indexOf(' '),(s.length()-1));
s=s.trim();
s=s+" ";
}
while(s.compareTo(" ")!=0);
return ns;
}
public static void main (String[] args)throws IOException
{
Encryption call=new Encryption();String s="";
call.enter();
if(call.n>1||call.n<10)
{
for(int i=0;i<call.a.length;i++)
{
if(i%2==0)
s=call.Encryption_by_two(call.a[i]);
else
s=call.reverse(call.a[i]);
System.out.println(s);
}
}
    }
}

No comments:

Post a Comment