import java.io.*;
class caesercipher
{
String str; int key;
public void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("ENTER A STRING");
str=br.readLine();
System.out.println("ENTER A SHIFT");
key=Integer.parseInt(br.readLine());
String encrypted=encrypt(str,key);
System.out.println(encrypted);
String decrypted=decrypt(encrypted,key);
System.out.println(decrypted);
}
public String encrypt(String str,int key)
{
String encrypted="";
int i;
for(i=0;i<str.length();i++)
{
int c=str.charAt(i);
if(Character.isUpperCase(c))
{
c+=(key%26);
if(c>'Z')
c=c-26;
}
else if(Character.isLowerCase(c))
{
c=c+(key%26);
if(c<'z')
c=c-26;
}
encrypted+=(char)c;
}return encrypted;}
public String decrypt(String str,int key)
{
String decrypted="";
int i;
for(i=0;i<str.length();i++)
{
int c=str.charAt(i);
if(Character.isUpperCase(c))
{
c=c-(key%26);
if(c<'A')
c+=26;
}
else if(Character.isLowerCase(c))
{
c=c-(key%26);
if(c<'a')
c+=26;
}
decrypted+=(char)c;
}
return decrypted;
}
}

for input
str=i am boy
key=3
output is
r jv kxi
o gs hui

but this doesnot satisfy caeser cipher pls help

Recommended Answers

All 2 Replies

Please use the 'CODE' tag... There are things that are not properly formatted or not working here.

1)Are you coding it using Object Oriented style? If so, you need a constructor for your class; otherwise, move those class variables inside your main().

2)You should have 'static' for your main() method.

3)It is better to always keep the main to accept arguments (good habit).

public static void main(String[] args) throw Exception {
  String str;
  int key;
  ...
  ...
}

4)The line consists of c+=(key%26); and c-=(key%26); are the problem. You need to know what boundary of your character is. When you step the character up or down, you need to check if the value passes the limit you have drawn. You get the right concept, but the way you do is to add the 'key' to the character anyway -- c = c + (key%26). Assume that you are checking only English alphabet. It won't work for other languages.

// this would satisfy upper case letter
c = (c+key)>'Z' ? (c+key-26) : (c+key);
// it is the same as...
if ((c+key)>'Z')
  c = c+key-26;
else
  c = c+key;

i am very sorry i had made a foolish mistake in line 34..
instead of if(c<'z') it should have been i(c>'z')

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.