【发布时间】:2016-02-06 14:31:04
【问题描述】:
我正在尝试制作一个密码,您在其中输入一个单词,它会根据用户选择的任何内容进行转换,但我收到此错误:
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:2
在 java.lang.String.charAt(未知来源)
在 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));
}
}
【问题讨论】:
-
因为你没有给它一个 25 个字符的输入。错误信息很清楚,调试器会解释更多
-
调试器没有帮助。将所有数字 25 更改为 26,在线程“main”中出现此错误异常 java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.String.charAt(Unknown Source) at cipher.mycipher.main(mycipher .java:24)
-
您知道,您的代码不会担心输入的长度,对吧?如果它的长度不是至少 25(或 26)个字符,它就会失败。
-
@JoshInttap
String original = consolereader.nextLine();-- 这里是减少的长度,而不是数组。如果输入 4-char 输入,那么应该从 0 迭代到 3,而不是 24。 -
@xoce 请不要在帖子中突出显示正常测试。将 "Here is my code:" 编辑成粗体文本绝对没有任何价值。
标签: java caesar-cipher