【问题标题】:I am trying to search up to the right diagonally in my multidimensional array in java. Why am I getting index out of bounds error?我正在尝试在 java 中的多维数组中向右对角搜索。为什么我的索引越界错误?
【发布时间】:2014-12-05 16:58:27
【问题描述】:

我正在尝试在 java 中的多维字符数组中对角向上搜索。我添加了一个 if 语句以确保它保持在数组的范围内,但是我得到一个索引超出范围的错误。谁能告诉我我的代码有什么问题?

        // search diagonal up to right
    if ((row - 1 >=0) && (col + 1 <= board[col].length)) {
        boolean foundWord = true;

        for (int letters = 0; letters < word.length(); letters++) {
            if (word.charAt(letters) != board[row - 1][col + 1]) {
                foundWord = false;
                break;
            }
        }
        if(foundWord) {
            return word + " Found at: " + Arrays.toString(new int[] {row,col});
        }
    } // end search diagonal up to right

【问题讨论】:

    标签: java search multidimensional-array indexoutofboundsexception


    【解决方案1】:

    我想通了。这是我的解决方案。

    这一行:

    if ((row - 1 >=0) && (col + 1 <= board[col].length)) {
    

    改成这样了:

    if((row - word.length() <= 0) && (col + word.length() <= board[row].length)) {
    

    【讨论】:

      【解决方案2】:

      java 中的数组是从零开始的,即它们的索引从零开始,因此最高索引是length - 1

      将比较运算符从&lt;= 更改为&lt;,这样就达不到length

      if ((row - 1 >=0) && (col + 1 = board[col].length)) {
      //                             ^---- change here
      

      【讨论】:

      • 我的索引仍然超出范围。
      【解决方案3】:

      数组编号从0开始,所以这里col + 1 &lt;= board[col].length你应该使用board[col].length-1

      【讨论】:

      • 我的索引仍然超出范围。
      • 您能否指定,您在哪一行代码中得到它?可能不是那行,而是内循环中的 word.length()
      • 它说我在这一行得到它:if ((row - 1 >=0) && (col + 1
      • 如果您将代码更改为 'board[col].length - 1',那么一定是 'board[col]' 导致了该错误。试试看
      猜你喜欢
      • 2014-12-04
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多