创建密码,但返回错误

Creating a cipher, but returning 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)

我不确定为什么会出现此错误?

这是我的代码:

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));
    }
}

您必须添加条件

 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];
            }
 }

不要超过原始长度,否则 for 循环将迭代到 25。

执行的迭代应基于原始长度而不是 25。

循环内的逻辑看起来很混乱。如果您解释清楚,我可以尝试为您提供工作代码。