the following code gets the multiplier and constant from the user and uses
them for encoding.
import java.io.*;
public class CaesarCipher
{
private static int multi;
private static int constant;
private static int findNum(char a)
{
String S="abcdefghijklmnopqrstuvwxyz";
int ret_val=S.indexOf(a);
return ret_val;
}
private static char findChar(int a)
{
String S="abcdefghijklmnopqrstuvwxyz";
char ret_val=S.charAt(a);
return ret_val;
}
public static void initMultiplier() throws IOException
{
String S;
DataInputStream dis = new DataInputStream(System.in);
System.out.println(" Enter the multiplier ");
S=dis.readLine();
multi=Integer.parseInt(S);
}
public static void initConstant() throws IOException
{
String S;
DataInputStream dis = new DataInputStream(System.in);
System.out.println(" Enter the constant ");
S=dis.readLine();
constant=Integer.parseInt(S);
}
public static String encoder(String c)
{
int coded;
int temp;
StringBuffer S=new StringBuffer();
String C;
c=c.toLowerCase();
for(int index=0;index < c.length();index++)
{
temp=findNum(c.charAt(index));
if(temp!=-1)
{
coded = multi * findNum(c.charAt(index)) + constant;
if(coded > 25)
{
temp = coded/26;
coded = coded - (temp*26);
}
S.append(findChar(coded));
}
else
S.append(" ");
}
C=new String(S);
C=C.toUpperCase();
return C;
}
public static String decoder(String C)
{
double decoded;
String c;
StringBuffer s=new StringBuffer();
double multi_recip = 1.0 / multi;
C=C.toLowerCase();
for(int index=0; index < C.length(); index++)
{
decoded = findNum(C.charAt(index));
if(decoded!=-1)
{
decoded=decoded - constant;
while(decoded % multi != 0 || decoded < 0)
{
decoded=decoded+26;
}
decoded = decoded / multi;
if(decoded > 25)
{
multi_recip = decoded/26;
decoded = decoded - (multi_recip*26);
}
s.append(findChar((int)decoded));
}
else
s.append(" ");
}
c=new String(s);
c=c.toUpperCase();
return c;
}
public static void main(String[] args)
{
String S;
String encoded;
String decoded;
DataInputStream dis=new DataInputStream(System.in);
try
{
S=dis.readLine();
System.out.println("String ="+ S);
initMultiplier();
initConstant();
encoded=encoder(S);
System.out.println(" Encoded format ="+ encoded);
decoded=decoder(encoded);
System.out.println(" Decoded format ="+ decoded);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}