Results 1 to 7 of 7
  1. #1
    chrisgoad3882 is offline Member
    Join Date
    Mar 2013
    Posts
    4
    Rep Power
    0

    Default Cipher and Decipher java.lang.StringIndexOutOfBoundsException

    I am currently having trouble with my Computer Science Assingment. The Encryption code works fine but when I try the Decryption code I get a java out of bounds exception. Please Help.

    Java Code:
    /**
    * This class tests CaesarShiftEncryption and CaesarShiftDecryption classes
    *
    * @author Christopher Goad
    * @version 3-13-12
    */
    
    import java.io.File;
    import java.util.Scanner;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.io.PrintWriter;
    public class ChrisGoadCipherTester
    {
        //constant for the alphabet
        public static ArrayList<Character> alphabet = makeAlphabet();
       
        public ChrisGoadCipherTester()
        {
        }
       
        public static ArrayList<Character> makeAlphabet()
        {
            ArrayList<Character> alphabet = new ArrayList<Character>();
            int letter = 65;
            for (int loop = 0; loop < 26; loop++)
            {
                alphabet.add((char)letter);
                letter++;
            }
            return alphabet;
        }
        
        public static void main(String[] args) throws IOException
        {
            Scanner in = new Scanner(System.in);
            //Menu for the user
            System.out.println("===============================");
            System.out.println("     [A] Chris Goad Cipher ");
            System.out.println("     [B] Chris Goad Decipher ");
            System.out.println("           [Q] Quit           ");
            System.out.println("===============================");
            System.out.print("Please select an letter option from the above menu and hit enter: ");
           
            String input = in.next();
            if (input.equalsIgnoreCase("A"))
            {
                ChrisGoadCipher.getInput();
            }
            else if (input.equalsIgnoreCase("B"))
            {
                ChrisGoadDecipher.getInput();
            }
            else if (input.equalsIgnoreCase("Q"))
            {
                System.out.println("You chose to quit. Goodbye!");
            }
            else
            {
                System.out.println("You did not choose a vaild option.");
            }
        }
    }
    Java Code:
    /**
    * This class is used to encrypt messages with a Caesar shift number.
    *
    * @author Christopher Goad
    * @version 3-13-12
    */
    
    import java.io.File;
    import java.util.Scanner;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.io.PrintWriter;
    public class ChrisGoadCipher
    {
        private static ArrayList<Character> newAlphabet = new ArrayList<Character>();
        private static ArrayList<Character> alphabet = ChrisGoadCipherTester.alphabet;
        
        public ChrisGoadCipher()
        {   
            
        }
       
        public static void getInput() throws IOException
        {
            //Ask for user input and call required methods
            Scanner in = new Scanner(System.in);
            createNewAlphabet();
            System.out.println("Here is the alphabet being used for encryption:");
            PrintWriter outA = new PrintWriter("cipherAlphabet.txt");
            displayNewAlphabet(newAlphabet);
            outA.println(newAlphabet);
            outA.close();
            System.out.print("\nEnter the phrase that will be encrypted: ");
            String message = in.nextLine();
            String newMessage = encrypt(message);
            System.out.println("Here is the encrypted message using the cipher alphabet: ");
            PrintWriter outM = new PrintWriter("cipherMessage.txt");
            System.out.println(newMessage + "\n");
            outM.println(newMessage);
            outM.close();
        }
       
        public static void createNewAlphabet()
        {
            int number;
            while(alphabet.size() > newAlphabet.size())
            {
                number = (int)(Math.random() * 26);
                if(newAlphabet.contains(alphabet.get(number)))
                {    
                    newAlphabet.remove(alphabet.get(number));
                }
                else 
                {
                    newAlphabet.add(alphabet.get(number));
                }
            }
        }
       
        public static void displayNewAlphabet(ArrayList<Character> newAlphabet)
        {
            for (int loop = 0; loop < 26; loop++)
            {
                System.out.print(newAlphabet.get(loop));
            }
        }
      
        public static String encrypt(String message)
        {
            String upper = message.toUpperCase();
            String newMessage = "";
            char newLetter;
            char letter;
            int letterPosition;
            //Runs through the message and encrypts it
            for (int loop = 0; loop < message.length(); loop++)
            {
                if(upper.charAt(loop) >= 65 && upper.charAt(loop) <= 90)
                {
                    letterPosition = alphabet.indexOf(upper.charAt(loop));
                    newMessage += newAlphabet.get(letterPosition);
                }
                else
                {
                    newMessage += upper.charAt(loop);
                }
            }     
            return newMessage;
        }
    }
    Java Code:
    /**
     * This class is used to decrypt messages with a Caesar shift number.
     * 
     * @author Christopher Goad
     * @version 3-13-12
     */
    
    import java.io.File;
    import java.util.Scanner;
    import java.util.ArrayList;
    import java.io.IOException;
    import java.io.PrintWriter;
    public class ChrisGoadDecipher
    {
        private static ArrayList<Character> cipherAlphabet = new ArrayList<Character>();
        private static ArrayList<Character> alphabet = ChrisGoadCipherTester.alphabet;
        
        public ChrisGoadDecipher()
        {   
            
        }
       
        public static void getInput() throws IOException
        {
            createcipherAlphabet();
            System.out.println("Here is the alphabet being used for decryption:");
            displayNewAlphabet(cipherAlphabet);
            String message = message();
            String newMessage = decrypt(message);
            System.out.println("Here is the decrypted message using the cipher alphabet: ");
            System.out.println(newMessage + "\n");
        }
        
        public static String message() throws IOException
        {
            File file = new File("cipherMessage.txt");
            Scanner in = new Scanner(file);
            String message = "";
            while(in.hasNext())
            {
                message = in.nextLine();
            }
            return message;
        }
        
        public static void displayNewAlphabet(ArrayList<Character> newAlphabet)
        {
            for (int loop = 0; loop < 26; loop++)
            {
                System.out.print(cipherAlphabet.get(loop));
            }
        }
        
        public static void createcipherAlphabet() throws IOException
        {
            File file = new File("cipherAlphabet.txt");
            Scanner in = new Scanner(file);
            while(in.hasNext())
            {
               String character = in.next();
               if(character == ","){}
               else if(character == "["){}
               else if(character == "]"){}
               else 
               {
                   String alphabet = "abcdefghijklmnopqrstuvwxyz";
                   int num = alphabet.indexOf(character);
                   String letter = alphabet.substring(num, num+1);
                   for (char c : letter.toCharArray()) 
                   {
                       cipherAlphabet.add(c);
                    }
               }
            }
            
        }
        
        public static String decrypt(String message)
        {
            String upper = message.toUpperCase();
            String newMessage = "";
            char newLetter;
            char letter;
            int letterPosition;
            //Runs through the message and encrypts it
            for (int loop = 0; loop < message.length(); loop++)
            {
                if(upper.charAt(loop) >= 65 && upper.charAt(loop) <= 90)
                {
                    letterPosition = alphabet.indexOf(upper.charAt(loop));
                    newMessage += cipherAlphabet.get(letterPosition);
                }
                else
                {
                    newMessage += upper.charAt(loop);
                }
            }     
            return newMessage;
        }
    }

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,172
    Rep Power
    20

    Default Re: Cipher and Decipher java.lang.StringIndexOutOfBoundsException

    Can you give us the full exception and stack trace.
    Highlight the line on which it occurs in your code.

    You might also want to stick some debugging code int here to see what values you are using.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    chrisgoad3882 is offline Member
    Join Date
    Mar 2013
    Posts
    4
    Rep Power
    0

    Default Re: Cipher and Decipher java.lang.StringIndexOutOfBoundsException

    When using option B to decrypt the message I am getting a java.lang.StringIndexOutOfBoundsException: String Index out of range: -1 (in java.lang.String). This occurs on this line
    Java Code:
     String letter = alphabet.substring(num, num+1);
    in the decryption class

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,172
    Rep Power
    20

    Default Re: Cipher and Decipher java.lang.StringIndexOutOfBoundsException

    Then 'num' seems to be -1 at that point.
    Which means whatever letter you are looking for is not in the String, so you shouldn't be attempting to substring based on that.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    chrisgoad3882 is offline Member
    Join Date
    Mar 2013
    Posts
    4
    Rep Power
    0

    Default Re: Cipher and Decipher java.lang.StringIndexOutOfBoundsException

    How could you fix this? Could you show me?

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,172
    Rep Power
    20

    Default Re: Cipher and Decipher java.lang.StringIndexOutOfBoundsException

    No idea what you are trying to do, or the logic behind it all, but this is your problem:
    Java Code:
    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    int num = alphabet.indexOf(character);
    String letter = alphabet.substring(num, num+1);
    Print out the value of 'character', because I would argue it is not a lowercase letter of the alphabet at the point this crashes.
    Hence 'num' is -1.

    And once you know what the value is then you might be able to figure out why it is wrong (assuming it is wrong).
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    chrisgoad3882 is offline Member
    Join Date
    Mar 2013
    Posts
    4
    Rep Power
    0

    Default Re: Cipher and Decipher java.lang.StringIndexOutOfBoundsException

    In the encryption class I have to create a randomly generated alphabet and then cipher a message with it both the alphabet and the message are saved to a text file. Now in the decryption class I have to read them back and decipher the message with the alphabet. Would you examine my code and see how to accomplish this?

Similar Threads

  1. Random-Letter Decipher Program Problems.
    By ssrock64 in forum New To Java
    Replies: 0
    Last Post: 02-21-2013, 12:37 AM
  2. Replies: 2
    Last Post: 05-07-2012, 07:31 PM
  3. Replies: 3
    Last Post: 09-11-2011, 10:15 AM
  4. Decipher this bit of code for me?
    By gandalf5166 in forum New To Java
    Replies: 2
    Last Post: 05-04-2010, 09:44 PM
  5. How to cipher a string without using Cipher class?
    By arnab321 in forum New To Java
    Replies: 1
    Last Post: 09-09-2009, 12:19 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •