的StringIndexOutOfBoundsException

我在使Java方法正常工作方面遇到了一些问题。 在程序中,我创建了一个由不同长度的许多不同单词组成的数组。 我正在处理的方法应该读取字长,字母和位置的用户输入,然后Java将打印出与这三个参数匹配的任何单词(例如,如果用户键入字长4,字母A和位置2,并且将打印出包含位置2处字母A的长度为4的单词。

无论如何,我创建的方法如下所示:

public static void inputMethod(int length, char letter, int position){ for (int index = 0; index < wordTable.length; index++) { if (length == wordTable[index].length() && letter == wordTable[index].charAt(position) ) System.out.println(wordTable[index]); } 

此方法适用于某些输入,但对于其他输入,我收到如下错误消息:

 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.String.charAt(Unknown Source) at Wordarray.inputMethod(Wordarray.java:153) at Wordarray.main(Wordarray.java:61) 

如果有人能向我解释我如何解决这个问题,我将不胜感激! 就像我说的那样,我只收到某些输入信息。 对于其他输入,程序就像它应该的那样工作。

如果你已经更换了

 for (int index = 0; index < wordTable.length; index++) { 

 for (int index = 0; index < length; index++) { 

这很可能不是你真正想要的。

更好的方法是这样的:

 public static void inputMethod(int length, char letter, int position) { // check if input is valid if(position < length) for (int index = 0; index < wordTable.length; index++) { if (length == wordTable[index].length() && letter == wordTable[index].charAt(position) ) System.out.println(wordTable[index]); } 

好吧,显然position大于在wordTable[index] (或负数)找到的字符串的长度。 您还需要检查字符串的长度。

如果给定位置大于或等于当前字的长度,则可能发生这种情况。 另外值得一看:第一个字符的position0还是1

这是你的实际代码吗? 您正在使用三个不同的变量:for循环中的indexindeksindex 。 我很惊讶这甚至编译。 不要重新键入代码,剪切并粘贴实际代码。