的StringIndexOutOfBoundsException [英] StringIndexOutOfBoundsException

查看:232
本文介绍了的StringIndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am having a few problems in getting a method to work properly in Java. In the program I have created an array consisting of many different words of different length. The method I'm working on is supposed to read user input for wordlength, letter, and position, and Java will then print out any words matching these three parameters (for instance, if the user types wordlength 4, letter A and position 2, and words with length 4 containing the letter A at position 2 will be printed out).

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

Anyhow, the method I have created looks like this:

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

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

This method works fine for for some inputs, but for other inputs I get an error message such as this:

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)

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

If anyone could explain to me how I can fix this, I would greatly appreciate it! Like I said, I only get this message for certain inputs. For other inputs the program works just like it is supposed to.

推荐答案

如果你已经替换了

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

with

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

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

that is most likely not what you really want.

更好的方法是这样的:

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

这篇关于的StringIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆