-1

I wrote a method to encrypt messages (using CaesarCipher) and I want to use that method to encrypt one message with all possible 26 keys. So I want to iterate over each String array to define it.

public String[] getMessage(String message) {
    String[] newMessage = new String[26]; 
    int index = 0; 
    for (int k = 0; k < message.length(); k++){
        newMessage[index] = encryptMessage(message, index);
        index+= 1; 
    }
    return newMessage;
}

But I get an ArrayIndexOutOfBoundsException.

What am I doing wrong?

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • I think you want `newMessage[k]`. You can also use `k` instead of `index` in `encryptMessage()`, `newMessage[k] = encryptMessage(message, k); ` – Guy Dec 06 '18 at 13:24
  • 1
    you are iterating until `k < message.length()`, shouldn't it be `k < newMessage.length`? – deHaar Dec 06 '18 at 13:25

2 Answers2

3

But i get an Array Index Out Of Bounds Exception

You're looping k from 0 until message.length()'s return value (exclusive), but you're using it to index into newMessage, which has a max index of 25. Clearly, the message string is more than 26 characters long, so k goes to > 25, which is why you're going out of bounds.

Limit k by the length of what you're indexing into, not the length of the string. Or, if the array is supposed to be the same length as the string, create it with new String[message.length()] rather than new String[26]. (I'd still change the loop to use < newMessage.length in that case, but it becomes a matter of style if they have the same length.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thank you, I understand a bit more how arrays work and I got the result that I was looking for! – Clémentine Boulot Dec 06 '18 at 13:42
  • @ClémentineBoulot If this Answer solves your Question, click the big green checkmark to accept, and thereby mark the Question as resolved. If you found your own solution, please write it up as an Answer of your own, and accept that. – Basil Bourque Dec 06 '18 at 16:58
1

The array starts with zero first. You set the size to 26. The last index of the array is then 25. That is, it ends with 0,1,2,3,...,24,25. Therefore, you must make a long-1 for a repeat sentence.

J.JH
  • 11
  • 1