0

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;
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Firefox
  • 11
  • 1
  • If you go until length-1 you must not then use i+1 in the loop meaning you access index length because that does not exist: – luk2302 Oct 16 '22 at 06:23
  • By reaching the last letter of the string, there is no more i+1 therefore it will lead to the error, change it to i only instead. – YUNG FOOK YONG Oct 16 '22 at 06:40

0 Answers0