I keep getting a "java.lang.StringIndexOutOfBoundsException" even though my for loop counter adjusts for length by subtracting 1

Nelly_Boi18 :

So my main goal is to create a program that can decrypt a caesar cipher. I have everything set up so that I have the regular alphabet set up in one array and then a decoder array where I have shifted the alphabet based on a shift/key the user inputs. (ie. if the user inputs a shift of 6, the regular alphabet array starts a, b, c... and then the decoder array starts g, h, i...).

I am currently stuck on going through the encrypted message (user inputted) and decoding each letter one by one by matching it up to the decoder array. It keeps giving me an index out of bounds error even though in the for loop that I have set up, I have subtracted one from the length of the message to compensate for it starting at 0.

The error only happens at the last character too (that's what the 35 is. I have a 35 character string that I'm using to test). But when I try to print the decoded message up until the error, I'm just getting nulls (I'm storing each decoded char in an array and print each character stored as the for loop is running).

Here is the piece of code that I'm currently stuck on:

//Decoding message by looping through each letter in String message
for (int x = 0; x < (message.length() - 1); x ++) //Gets next letter in message
{
    for (int y = 0; y < (decodedArray.length - 1); x++) //Goes through decodedArray array
    {
        if (String.valueOf(message.charAt(x)) == (decodedArray[y])) //Comparing character to each position in decodedArray
        {
            decodedMessage[x] = alphabetArray[y];
        }
        System.out.print(decodedMessage[x]); //Testing only. Prints each character stored in array but only printing nulls.
    }
}

I haven't added any checks for spaces yet because I'm currently stuck on this error but if any of you can add that, that would be greatly appreciated. I'm not sure if comparing a char to a space would work.

Prakhar Londhe :

According to the current code in the question, I can say there are 2 problems with your code,

  1. If you need to compare char, you can directly use to == operator without needing it to convert it to string by using String.ValueOf().

  2. You are incrementing x in the 2nd loop, instead you need to increment y

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3576&siteId=1