首页 > 解决方案 > 填充数组中的空白值

问题描述

我创建了一个二维数组(称为names)来存储字符串值。最初,我将数组中的所有元素分配给空白。为此,我有一个变量来存储最大行数并遍历数组,用空格填充其元素。

public class Untitled
{
    public static void main(String[] args) 
    {
        int maxRows = 10 ;

        String names[][] = new String[maxRows][2] ;

        int y = 0 ;
        while(y <= maxRows)
        {
            int x = 0 ;
            while (index < 2)
            {
                names[y][x] = " " ;
                index++ ;               
            }

            counter++ ;
        }       
    }
}

但是,一旦代码编译并运行,我会收到一条错误消息“线程“主”java.lang.ArrayOutOfBoundsException:10 中的异常”

标签: javaarraysstring

解决方案


Change y <= maxRows to y < maxRows. The highest index is 9 in an array of 10 elements. You will also need to change counter++ to y++ in order to increment y.

Also, x never changes, so you are only filling the first column with blanks. You should change index < 2 to x < 2 and index++ to x++.

Finally, I suggest you learn about for loops.


推荐阅读