Results 1 to 9 of 9
  1. #1
    GoodGuyGreg is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default ArrayOutOfBounds error and I don't know where its coming from!

    Hey, I'm writing a program that encrypts sentences with keyword by adding the keywords character value to each character in the string. Problem is I want it to encrypt more than one sentence and to do that I need an Array. I've only just started with Arrays so I need some help.
    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    public class BeatonCode
    {
        public static void main (String [] args) throws IOException
        {
            EncryptionKeyC enc = new EncryptionKeyC ();
            boolean carryon;
            String inputNum = " ";
            int size = 0;
            
            
            while (true)
            {
                String inputChoice = JOptionPane.showInputDialog ("A.Encrypt with Keyword Cipher \n B.Decrypt with Keyword Cipher \n C.Encrypt with JayCipher \n D.Decrypt with JayCipher \n E. Exit program.");
                try
                {
                    if (inputChoice.compareToIgnoreCase ("A") == 0)
                    {
                        String keyCWord = JOptionPane.showInputDialog ("Enter the keyword : ");
                        try
                        {
                        inputNum = JOptionPane.showInputDialog ("How many sentences : ");
                        size = Integer.parseInt (inputNum);
                        }
                        catch (NumberFormatException numErr)
                        {
                         inputNum = JOptionPane.showInputDialog ("Only whole numbers please! : ");
                        size = Integer.parseInt (inputNum);
                        }
                       String[] allData = new String [size];
    
                        for (int i = 0 ; i < size ; i++)
                        {
                            String sentence = JOptionPane.showInputDialog ("Enter your sentence ");
    
                            allData [i] = sentence;
                            
                        }
    
                       String nwAllData[] = enc.Encrypt (allData, keyCWord,size); <--[B] Ikeep getting an array out of bounds error here.[/B]
    [B][I]This is the method I call for the encryption:[/I][/B]
        public String[] [B]Encrypt[/B] (String data[], String keyW,int s)
        {
            String allData[] = data;
            String keyCWord = keyW;
            int size = s;
           
            int lenStr = allData[size].length();
            int lenKey = keyCWord.length ();
            System.out.print(lenStr);
           String encryptedStr = "";
    
            // For each character in our string, encrypt it...
            for (int i = 0, j = 0 ; i < lenStr; i++, j++)
            {
                //Allows keyword to be used over again and again.
                if (j >= lenKey)
                {
                    j = 0;
                }
                
                //Add the characters from the key from the original string
                //Cast it back into a character
                //Add it to the new string
    
              char test = (char) (allData[size].charAt (i) + keyCWord.charAt (j));
               encryptedStr += test + "";
              
            }
    
           return allData;
        }
    TL;DR : Just check out the second class where the method Encrypt is and see if you can find out what causes the arrayoutofbounds error thanks!
    Last edited by pbrockway2; 11-13-2011 at 08:45 PM. Reason: code tags added

  2. #2
    GoodGuyGreg is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Re: ArrayOutOfBounds error and I don't know where its coming from!

    Okay the error is definitely coming from this part int lenStr = allData[size].length(); I need this to determine how many characters there is in the Array allData so i can make that the max of my forloop where i add the keywords values to each character.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: ArrayOutOfBounds error and I don't know where its coming from!

    Hi Greg, welcome.

    Please use the "code" tags when posting code. You put [code] at the start of the code and [/code] at the end. That way the code will be formatted properly. It is also a good idea to use spaces rather than tabs to indent as web browsers tend to render tabs rather generously.

    Also the best way of describing a runtime error to is to post the full stack trace.

  4. #4
    GoodGuyGreg is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Re: ArrayOutOfBounds error and I don't know where its coming from!

    Thanks Mr.Brockway.

    I'll be sure to do that in the future, as for my problem i just reverted all of the arrays to string and added a += "\n" to the for-loop so it starts every sentence on a new line. Now I've got a different problem.
    Java Code:
     // For each character in our string, encrypt it...
             for (int i = 0, j = 0 ; i < lenStr; i++, j++)
              {
                 //Allows keyword to be used over again and again.
                if (j >= lenKey)
                {
                    j = 0;
                }
                
               //Add the characters from the key from the original string
               //Cast it back into a character
               //Add it to the new string
             
              char test = (char) (allData.charAt (i) + keyCWord.charAt (j));
              encryptedStr += test + "";
              
            }
    So because I'm adding the keyword values to every character in my sentences the spaces also wind up being some unknown character, RTP Java doesnt know what that character is so it turns it into a square, this squares value is in the 1000's so when i subtract the keyword to decrypt the sentences it doesn't revert to spaces. Any ideas?
    Last edited by GoodGuyGreg; 11-13-2011 at 09:14 PM.

  5. #5
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: ArrayOutOfBounds error and I don't know where its coming from!

    Java Code:
    public String[] encrypt(String data[], String keyW, int s)
    {
        String allData[] = data;
        String keyCWord = keyW;
        int size = s;
    
        int lenStr = allData[size].length();
    
        // some stuff
    
        return allData;
    }
    There's actually a few things about that method that stand out. Your ArrayIndexOutOfBounds exception is just one of them.

    (1) Start method with a lower case letter: encrypt. (And consider the more common array declarations "String[] data" in place of "String data[]")

    (2) There is no need to pass the s argument to this method, as this is just the length (size) of the data array. You might as well just declare

    Java Code:
    int size = data.length;
    (3) "allData[size].length();" will throw the ArrayIndexOutOfBoundsException becuase the allData data (which is exactly the same as the data array) has length size, and therefore it's indices run from zero to size-1. Ie there is no such element as allData[size].

    (4) You pass an array to this method, do some stuff and then return the very same array, which seems a bit redundant. Either initialise allData to be a new array and return that (if that is what you mean to do), or don't bother returning anything since the caller already has a reference to the newData array (it's the same as the data array they passed).

    -----

    Maybe you could step back from this method and begin again by describing precisely what it is supposed to do: (1) What each of the arguments it is passed represent, and (2) What the value it returns represents. Only then worry about how that might be achieved.

    [Edit] some of this s-l-o-w-l-y composed post doesn't apply as there is no array now
    Last edited by pbrockway2; 11-13-2011 at 09:23 PM.

  6. #6
    GoodGuyGreg is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Re: ArrayOutOfBounds error and I don't know where its coming from!

    Don't worry Mr. Brockway.

    I did make a backup of the one with the array so i can just edit that. Using the array was what I intended and with your help I can fix it :D, Thanks a bunch.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: ArrayOutOfBounds error and I don't know where its coming from!

    What's this RTP Java?

    If you find that funny squares appear in the encrypted strings this may simply be a matter of how those strings appear when they are drawn on the screen. It's a good idea with a program like this to start with the encrypt() and decrypt() methods and forget all the other stuff that main() is supposed to do (for an assignment or whatever). Instead have main() hard code some data (a string or an array of strings), encrypt() them, decrypt() the result and finally check that it ends up with what it started with. If anything goes wrong you then have compilable, runnable code that you can post.

    Once these methods - which form the guts of your program - are good you can write the main() method to do whatever it is supposed to do.

    Personally I would concentrate on methods that encrypt() and decrypt() a single string as that is easier to think about. Separate methods can be written later to deal with arrays of strings by calling the single string methods over and over. This is a general point: have your methods do as little as possible. It makes debugging a lot easier.

  8. #8
    GoodGuyGreg is offline Member
    Join Date
    Nov 2011
    Posts
    6
    Rep Power
    0

    Default Re: ArrayOutOfBounds error and I don't know where its coming from!

    RTP Java is Ready To Program Java, we use this at my school I've only got Grade 10 knowledge. We started using Arrays last week so that explains why I'm struggling. Anyhow I've gotten it to work check it out
    Java Code:
     
    public String[] encrypt (String[] data, String keyW)
        {
            String allData[] = data;
            String keyCWord = keyW;
           
    
            int lenStr = 0;
            allData = new String[lenStr];
            
            int lenKey = keyCWord.length ();
    
            String encryptedStr = "";
    
            // For each character in our string, encrypt it...
            for (int i = 0, j = 0 ; i < lenStr; i++, j++)
            {
                //Allows keyword to be used over again and again.
                if (j >= lenKey)
                {
                    j = 0;
                }
                
                //Subtract the characters from the key from the original string
                //Cast it back into a character
                //Add it to the new string
    
              char test = (char) (allData[i].charAt (i) + keyCWord.charAt (j));
               allData[i] += test + "";
            }
    
           return allData;
        }
    Thanks for the Quick replies!

  9. #9
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: ArrayOutOfBounds error and I don't know where its coming from!

    Java Code:
    int lenStr = 0;
    allData = new String[lenStr];
    That doesn't look right. The allData array you are going to return will have zero elements in it!

    There are three lengths that you have to keep straight. (1) the length of the key, lenKey (2) the length of the array that was passed, it is data.length but you aren't using it (you should) and (3) the length of the string you are currently encrypting, lenStr. This last one is what you are setting to zero. In fact its value varies from string to string.

    [Edit] If you are still thinking about how to do this encryption (and if you haven't got to meet specific requirements imposed by your teacher etc) I would strongly suggest writing two encryption methods: one to just encrypt a single string, and a second one (using the first) to encrypt a whole array of them. This will help you keep the three lengths clearly distinguished.
    Last edited by pbrockway2; 11-13-2011 at 10:56 PM.

Similar Threads

  1. Replies: 4
    Last Post: 11-10-2011, 06:43 PM
  2. where is 6 coming from
    By loja11 in forum Advanced Java
    Replies: 4
    Last Post: 10-16-2011, 03:48 PM
  3. ArrayOutofBounds Exception
    By aianta in forum New To Java
    Replies: 5
    Last Post: 08-12-2011, 08:14 PM
  4. i cant undersatand y this error is coming
    By RajeshReddy in forum AWT / Swing
    Replies: 0
    Last Post: 07-21-2011, 03:53 PM
  5. Jax is coming to the us!!!
    By blease87 in forum Reviews / Advertising
    Replies: 0
    Last Post: 03-04-2011, 01:21 PM

Posting Permissions

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