【问题标题】:multi dimensional array debugging outofboundsexception多维数组调试outofboundsexception
【发布时间】:2018-09-06 19:06:06
【问题描述】:

我正在尝试创建两个 3 x 3 数组(具有预定索引),它们将自行添加并显示输出,但我不断收到 OOBE(越界异常)错误

// The "Matrixsum" class.
import java.awt.*;
import hsa.Console;

public class Matrixsum
{
    static Console c;           // The output console

    public static void main (String[] args)
    {
        c = new Console ();

        int array[] [] = {{4, 5, 3}, {6, 8, 3}, {1, 2, 3}};
        int array1[] [] = {{5, 4, 3}, {5, 6, 3}{1, 2, 3}};

        c.println ("Number of Row= " + array.length);
        c.println ("Number of Column= " + array [1].length);

        int l = array.length;

        c.println ("\t\t\nMatrix 1 :\n ");
        for (int row = 0 ; row < l ; row++)
        {
            for (int col = 0 ; col <= l ; col++)
            {
                c.print (" " + array [row] [col]);
            }
            c.println ();
        }
        int L1 = array1.length;
        c.println ("Matrix 2 : ");
        for (int row = 0 ; row < L1 ; row++)
        {
            for (int col = 0 ; col <= L1 ; col++)
            {
                c.print (" " + array1 [row] [col]);
            }
            c.println ();
        }
        c.println ("Addition of both matrix : ");
        for (int row = 0 ; row < L1 ; row++)
        {
            for (int col = 0 ; col <= L1 ; col++)
            {
                c.print (" " + (array [row] [col] + array1 [row] [col]));
            }
            c.println ();
        }


        // Place your program here.  'c' is the output console
    } // main method
}

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    你正在做的任何地方col &lt;= L1col &lt;= l 需要更改为col &lt; L1col &lt; l

    数组的最大索引总是长度减一,因为数组索引从零开始。

    【讨论】:

    • 正确。这也可以通过调试并查看与数组大小相比变得过高的值来找到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多