This program is supposed to encrypt a string by injecting a random amount characters, followed by a key between each letter in the user chosen text. I realize that my code is flawed, as the decrypt method faces an error when given a String of duplicates, for example "aaa", and the key "a". It happens in the decrypt method, as I'm supposed to create a String consisting of any characters one index after the key. When this occurs I receive an index out of bounds error, because it is attempting to locate a character that does not exist(?). Is there a better approach to the problem? I'm new to programming and although I recognize what is going wrong, I simply can't think of a solution.
Can post the rest of code if necessary, any advice is very appreciated.
public static String decrypt(String ciphertext, char key) {
String decrypted = "";
int length = ciphertext.length();
for(int i = 0; i < length; i ++) {
if(ciphertext.charAt(i) == key) {
decrypted += ciphertext.charAt(i+1);
}
}
return decrypted;
}