StringIndexOutOfBoundsException

前端 未结 4 631
花落未央
花落未央 2021-01-29 09:03

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 met

相关标签:
4条回答
  • 2021-01-29 09:05

    If you have replaced

    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.

    The better approach would be like this:

    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]);
    }
    
    0 讨论(0)
  • 2021-01-29 09:10

    Well, obviously position is bigger than the length of the string that is found at wordTable[index] (or negative). You'll need to check against the length of the string too.

    0 讨论(0)
  • 2021-01-29 09:17

    If the given position is greater or equal than the length of the current word, this can happen. Also worth a look: Is the position for the first character 0 or 1?

    0 讨论(0)
  • Is this your actual code? You are using three different variables: indexs, indeks and index in your for-loop. I'm surprised this even compiled. Don't retype your code, cut and paste the actual code.

    0 讨论(0)
提交回复
热议问题