0

我需要创建一个用户可以编辑的动态二维数组。我尝试了许多不同的方法,甚至尝试单独进行以更容易诊断,但总是得到一个java.lang.ArrayIndexOutOfBoundsException. 下面是一些显示问题的代码(不是来自我的项目)。当我尝试用0.

public class Example {
    public static void main (String args[]) {
        int rows = 0;
        int cols = 0;
        int[][] board = new int[rows][cols];
        Scanner scan = new Scanner (System.in);

        System.out.print("Enter in a row  :");
        rows = scan.nextInt();
        System.out.print("Enter in a col :");
        cols =scan.nextInt();

        for (int i = 0; i < rows; i++)  {
            for (int j = 0; j < cols; j++)  {
            board[i][j] = 0;
                    System.out.print ("\t" + board[i][j]);                       
                } 
            System.out.print ("\n"); 
            }
        }
    }
4

3 回答 3

2

您正在用 0 行和 0 列初始化数组。那是一无是处。如果用户为行和列输入 1 和 1,则您尝试访问第一行。但是没有行。

您应该在从用户那里获得行数和列数后初始化您的板子。

int rows = 0; // the Java default value for integers is 0. Equivalent: int rows;
int cols = 0; // equivalent: int cols;

Scanner scan = new Scanner (System.in);

System.out.print("Enter in a row  :");
rows = scan.nextInt();
System.out.print("Enter in a col :");
cols =scan.nextInt();

int[][] board = new int[rows][cols]; // now has values other than 0

for (int i = 0; i < rows; i++)
{
   for (int j = 0; j < cols; j++) 
   {
      board[i][j] = 0;
      System.out.print ("\t" + board[i][j]);                         
   } 
   System.out.print ("\n"); 
}

理想情况下,您希望验证用户输入以查看他们提供的维度是否有意义。

于 2013-09-23T20:12:26.510 回答
1

当然你会得到一个ArrayIndexOutOfBoundsException. 您正在使用[0][0]维度初始化数组。仔细看看有什么价值rowscols有什么。

使固定:

最多允许n行和列m
例如int rows = 5, cols = 6

或者在您阅读rowscolsScanner.

发疯:

int rows = Integer.MAX_VALUE;
int cols = Integer.MAX_VALUE;
于 2013-09-23T20:12:06.040 回答
1

如果想,它应该是这样的:

public class Example {

    public static void main (String args[]) { 
        int rows = 0; 
        int cols = 0; 
        Scanner scan = new Scanner (System.in);

       System.out.print("Enter in a row  :");
       rows = scan.nextInt();
       System.out.print("Enter in a col :");
       cols = scan.nextInt();

       int[][] board = new int[rows][cols]; 

       for (int i = 0; i < rows; i++)
       {
           for (int j = 0; j < cols; j++) 
           {
               board[i][j] = 0;
               System.out.print ("\t" + board[i][j]);                         
           } 
           System.out.print ("\n"); 
       }
    } 
}
于 2013-09-23T20:17:33.150 回答