Search code examples
javacaesar-cipher

Creating a cipher, but returning error


I am trying to make a cipher, in which you type a word, and it gets shifted by whatever the user chooses, but I am getting this error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(Unknown Source)
at cipher.mycipher.main(mycipher.java:24)

I am not sure why I am getting this error?

Here is my code:

public class mycipher {

    public static void main(String[] args) {
        int[] storagelocation = new int[25];
        char[] letter1 = new char[25];
        char[] init = new char[25];
        Scanner consolereader = new Scanner(System.in);
        char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        System.out.println("what word would you like to cipher?");
        String original = consolereader.nextLine();
        System.out.println("how much would you like to shift it by");
        int shift = consolereader.nextInt();

        for (int i = 0; i < 25; i++) {
            storagelocation[i] = i;
            letter1[i] = letters[i];
            if (letter1[i] == (original.charAt(i))) {
                letter1[i] = init[i];
            }
        }
        System.out.println(Arrays.toString(init));
    }
}

Solution

  • You must add condition like

     for (int i= 0; i < original.length(); i++) {
                storagelocation[i] = i;
                letter1[i] = letters[i];
                if (letter1[i] == original.charAt(i)) {
                    letter1[i] = init[i];
                }
     }
    

    Do not excede lenght of the original else the for loop will iterate until 25.