0

I'm trying to make a simple Caesar cipher in java that accepts 2 arguments. One being the phrase, and the next being the shift of the letters.

I'm very new to Java, and I'm still trying to understand the basics. As a requirement, the cipher should keep capital letters capital, and lower case letters lower case. The space between words should also be left alone.

So far I have declared the the variable for the shift and have made 2 separate strings for lower case letters and uppercase letters. I'm not too sure where to proceed from here. Any help would be greatly appreciated.

public class caesar2{
public static void main(String args[]){
    String phrase = args[0];
    //First Argument
    String k = args[1];
    //Second argument
    //The shift of the letters in the caesar Cipher
    char characters[] = phrase.toCharArray();
    //Sending the input characters into a character array 
    int shift = Integer.parseInt(k);
    int remainder = shift % 26;
    //The shift = value K       
    for( int i=0; i < characters.length; i++)
    {
        if ((Character.isUpperCase(characters[i]))== true)
        {
            if((int)(characters[i]) + remainder >= 90)
            {
                characters[i] = (char)(characters[i]-(26-remainder));                   
            }
            else
            {
                characters[i] = (char)(characters[i]+remainder);
            }
        }
        else if (Character.isLowerCase(characters[i])==true)
        {
            if ((int)(characters[i] + remainder) >= 122)
            {
                characters[i] = (char)(characters[i] - (26-remainder));
            }
            else
            {
                characters[i] = (char)(characters[i]+remainder);
            }
        }   
    }
    for(int i =0; i< characters.length;i++)
        System.out.println (characters[i]);
    {
        }
}

}

user3245510
  • 9
  • 1
  • 1
  • 2
  • 6
    Don't ask us to solve your homework! Forget java for a minute. What is the algorithm you have in mind? Once you can do it mechanically by hand then translate that to java. – codesalsa Jan 28 '14 at 17:11
  • possible duplicate of [ROT-13 function in java?](http://stackoverflow.com/questions/8981296/rot-13-function-in-java) – Mike Samuel Jan 28 '14 at 17:14

5 Answers5

3

This code might help you run this in java editors like eclipse,netbeans since Scanner is used to take user input.

import java.util.Scanner;
public class CaeserCipher
{
public static void main(String[] args) 
{
    Scanner sc=new Scanner(System.in);
    String str;
    String key;
    int keyLength;

    System.out.println("Enter message:");
    str=sc.nextLine();
    System.out.println("Enter encryption key:");
    key=sc.next();
    keyLength=key.length();
    //This for loop is repeated use of 'Enrypt' and 'Decrypt' options
    for(;;)
    {
        System.out.println("1.Encrypt\n2.Decrypt\n3.Exit...");
        int choice=sc.nextInt();
        switch(choice)
        {
            case 1:
            /*send input string keyLength to encrypt() method to encrypt it returns 'Encrypted' string*/
                System.out.println("Encrypted message..."+encrypt(str,keyLength));
                break;
            case 2:
                //send retrived string from encrypt() method and keyLength to decrypt() method it returns 'Decrypted' string
                System.out.println("Decryptedmessage..."+decrypt(encrypt(str,keyLength),keyLength));
                break;
            case 3:
                //exit from the program
                System.exit(0);
                break;
            default:
            System.out.println("Invalid option..");
        }
    }
}
public static String encrypt(String str,int keyLength)
{
    String encrypted="";
    for(int i=0;i<str.length();i++)
    {
        //stores ascii value of character in the string at index 'i'
        int c=str.charAt(i);
        //encryption logic for uppercase letters
        if(Character.isUpperCase(c))
        {
            c=c+(keyLength%26);
            //if c value exceeds the ascii value of 'Z' reduce it by subtracting 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
            if(c>'Z')
                c=c-26;
        }
        //encryption logic for lowercase letters
        else if(Character.isLowerCase(c))
        {
            c=c+(keyLength%26);
            //if c value exceeds the ascii value of 'z' reduce it by subtracting 26(no.of alphabets) to keep in boundaries of ascii values of 'a' and 'z'
            if(c>'z')
                c=c-26;
        }
        //concatinate the encrypted characters/strings
        encrypted=encrypted+(char) c;
    }
    return encrypted;
}
public static String decrypt(String str,int keyLength)
{
    String decrypted="";
    for(int i=0;i<str.length();i++)
    {
        //stores ascii value of character in the string at index 'i'
        int c=str.charAt(i);
        //decryption logic for uppercase letters
        if(Character.isUpperCase(c))
        {
            c=c-(keyLength%26);
            //if c value deceed the ascii value of 'A' increase it by adding 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
            if(c<'A')
                c=c+26;
        }
        //decryption logic for uppercase letters
        else if(Character.isLowerCase(c))
        {
            c=c-(keyLength%26);
            //if c value deceed the ascii value of 'A' increase it by adding 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
            if(c<'a')
                c=c+26;
        }
        //concatinate the decrypted characters/strings
        decrypted=decrypted+(char) c;
    }
    return decrypted;
}
}
3

Encryption Part

import java.util.Scanner;

public class CaesarCipher {

   public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String plainText = in.nextLine();
   // key value should be from 0 to 25
    int key = in.nextInt();
    plainText = plainText.toUpperCase();
    char[] plainTextChar = plainText.toCharArray();
    for(int i=0;i<plainTextChar.length;i++) {
        plainTextChar[i] = (char)(((int)plainTextChar[i]+key-65)%26 + 65);
    }
    System.out.println(String.valueOf(plainTextChar));
 }  
}
2

First you don't need 2 arrays, you just need one of them, and keep state of capitalization (in a boolean isCapital for example).

Second, if you use an array of letters, that would be far easier to use for your problem.

char[] letters = {'A', 'B', 'C'...};

Then you just have to apply the shift to the index of the letter modulus the size of the array.

m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • what about keeping lower case letters lower case and capital letters upper case? will that help? – user3245510 Jan 28 '14 at 17:22
  • @HankDitton Processing a strings is way slower than accessing an array by index. – m0skit0 Jan 28 '14 at 17:33
  • @user3245510 You don't need that, you just convert all letters to uppercase but keep their case in a boolean (e.g. true uppercase, false lowercase) then update accordingly. – m0skit0 Jan 28 '14 at 17:34
  • is there a resource that I could use to get a better understanding of java syntax? that's really what's messing me up. I know what I want to do and how I want to do it, but I don't know how to type it up in java syntax. I want to turn each letter of each word into an integer, have a for loop check each integer, and then shift it over. If the integer goes past z, I then want to go back to A. – user3245510 Jan 28 '14 at 20:01
  • So with a little bit of help, I was able to get it, but it won't print out the results – user3245510 Jan 29 '14 at 00:02
1

I've found the relation to find the right letter by using the number of letters(26), the key/shift number and the letter you want to shift

You can put a String and then only letters (UPPER and lower) are shifted, all the rest of the characters will remain the same.

The key can be any int, also negative.

I hope it can help you, sorry for the bad English.

/**
 * byte constant wich means the number of letter in the alphabet
 */
private static final byte ALPHABET_LENGTH = 26;

/**
 * To encrypt the text
 * @param key int: the encryption key
 * @param text String: the text to encrypt 
 * @return String: the encrypted text
 */
public static final String encryptText(int key, String text) {
    StringBuilder cipherText = new StringBuilder();
    for(int i = 0; i < text.length(); i++) 
    {
        if(key >= 0) {
            if(Character.isLowerCase(text.charAt(i))) {
                cipherText.append((char) ('a' + ((text.charAt(i) - 'a' + key) %  AnticoCifrarioDiCesare.ALPHABET_LENGTH)));
            }
            else if(Character.isUpperCase(text.charAt(i))) {
                cipherText.append((char) ('A' + ((text.charAt(i) - 'A' + key) %  AnticoCifrarioDiCesare.ALPHABET_LENGTH)));
            }
            else {
                cipherText.append(text.charAt(i));
            }
        }
        else {
            if(Character.isLowerCase(text.charAt(i))) {
                cipherText.append((char) ('a' + (AnticoCifrarioDiCesare.ALPHABET_LENGTH + text.charAt(i) - 'a' + key % AnticoCifrarioDiCesare.ALPHABET_LENGTH) % AnticoCifrarioDiCesare.ALPHABET_LENGTH));
            }
            else if(Character.isUpperCase(text.charAt(i))) {
                cipherText.append((char) ('A' + (AnticoCifrarioDiCesare.ALPHABET_LENGTH + text.charAt(i) - 'A' + key % AnticoCifrarioDiCesare.ALPHABET_LENGTH) % AnticoCifrarioDiCesare.ALPHABET_LENGTH));
            }
            else {
                cipherText.append(text.charAt(i));
            }
        }
    }
    return cipherText.toString();
}
/**
 * To decrypt the text
 * @param key int: the key to decrypt
 * @param cipher String: the text to decrypt
 * @return String: the text decrypted
 */
public static final String decryptText(int key, String cipher) {
    StringBuilder rawText = new StringBuilder();
    for(int i = 0; i < cipher.length(); i++) 
    {
        if(key >= 0) {
            if(Character.isLowerCase(cipher.charAt(i))) {
                rawText.append((char) ('a' + (AnticoCifrarioDiCesare.ALPHABET_LENGTH + cipher.charAt(i) - 'a' - key % AnticoCifrarioDiCesare.ALPHABET_LENGTH) % AnticoCifrarioDiCesare.ALPHABET_LENGTH));
            }
            else if(Character.isUpperCase(cipher.charAt(i))) {
                rawText.append((char) ('A' + (AnticoCifrarioDiCesare.ALPHABET_LENGTH + cipher.charAt(i) - 'A' - key % AnticoCifrarioDiCesare.ALPHABET_LENGTH) % AnticoCifrarioDiCesare.ALPHABET_LENGTH));
            }
            else {
                rawText.append(cipher.charAt(i));
            }
        }
        else {
            if(Character.isLowerCase(cipher.charAt(i))) {
                rawText.append((char) ('a' + ((cipher.charAt(i) - 'a' - key) %  AnticoCifrarioDiCesare.ALPHABET_LENGTH)));
            }
            else if(Character.isUpperCase(cipher.charAt(i))) {
                rawText.append((char) ('A' + ((cipher.charAt(i) - 'A' - key) %  AnticoCifrarioDiCesare.ALPHABET_LENGTH)));
            }
            else {
                rawText.append(cipher.charAt(i));
            }
        }
    }
    return rawText.toString();
}
1
import java.io.DataInputStream;
//Done by Sridhar P
 public class Main {
  public static void main(String[] args)throws Exception {
   int key,choice,ascii=0,i,j,n,addascii;
   char c;
   String message="",encrypted="";
   System.out.println("choose a option:");
   System.out.println("1.Encrypt");
   System.out.println("2.Decrypt");
   System.out.println("3.Hack");
   DataInputStream din = new DataInputStream(System.in);
   choice = Integer.parseInt(din.readLine());
   switch(choice){
     case 1:
     {
      System.out.println("Enter the message to encrypt:");
      message = din.readLine();
      n=message.length();
      System.out.println("Enter the key [1-26]:");
      key = Integer.parseInt(din.readLine());
      char[] msg = message.toCharArray();
      for(i=0;i<n;i++)
      {
      ascii = (int) msg[i];
      addascii = key + ascii;
      c = (char) addascii;
      encrypted = encrypted + c; 
      }
      System.out.println("Encrypted text is :"+encrypted);
      break;
     }
    case 2:
    {
      System.out.println("Enter the message to decrypt:");
      encrypted = din.readLine();
      n=encrypted.length();
      System.out.println("Enter the key [1-26]:");
      key = Integer.parseInt(din.readLine());
      char[] msg = encrypted.toCharArray();
      for(i=0;i<n;i++)
      {
      ascii = (int) msg[i];
      addascii = ascii - key;
      c = (char) addascii;
      message = message + c; 
      }
      System.out.println("Decrypted text is :"+message);
      break;
    } 
    case 3:
    {
      System.out.println("Enter the message to decrypt:");
      encrypted = din.readLine();
      n=encrypted.length();
      char[] msg = encrypted.toCharArray();
      for(j=1;j<27;j++)
      {
      key=j;
      for(i=0;i<n;i++)
      {
      ascii = (int) msg[i];
      addascii = ascii - key;
      c = (char) addascii;
      message = message + c; 
      }
      System.out.println(j+" "+message);
      message="";
      }
    } 
   }
  }
}
Sridhar
  • 81
  • 1
  • 1