【问题标题】:Error: exception in thread 'main' java.lang.ArrayIndexOutOfBoundsException: 0 [closed]错误:线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:0 [关闭]
【发布时间】:2014-12-06 02:28:28
【问题描述】:
import java.util.Scanner;
public class TestMultiDimenArray
{
    private static int row;
    private static int column;
    public static int [][] table1 = new int [row][column];

    public static int [][] get ( int a, int b){
        row = a;
        column = b;
        Scanner keyboard = new Scanner(System.in);
        for (int n = 0; n < a; n++){
            for (int m = 0; m < b; m++){
                table1[n][m] = keyboard.nextInt();
            }
        }
        return table1;
    }

    public static void display (int [][] array1){
        for (int n = 0; n < row; n++){
            for (int m = 0; m < column; m++){
                System.out.print(table1[n][m] + " ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args){
            get(3,3);
    }
}

程序编译成功,但是当我运行它时,它返回错误。我该如何解决?这就是我能说的关于我的问题的全部内容。告诉我要提供更多细节的系统出了什么问题。

【问题讨论】:

  • 您是否尝试调试过您的程序?你觉得你在用public static int [][] table1 = new int [row][column];做什么?达到此语句时rowcolumn 的值是多少? Java 不是 Excel...

标签: java arrays runtime-error main


【解决方案1】:

该语句声明了一个长度为 0 宽度为 0 的二维数组。

public static int [][] table1 = new int [row][column];

这是因为 rowcolumn 在类初始化时还没有被赋值;只有在调用get 时才会分配它们。因此 Java 为它们分配了默认值 0

从参数中分配rowcolumn 值后初始化数组。

public static int [][] table1;

public static int [][] get ( int a, int b){
    row = a;
    column = b;
    table1 = new int [row][column];
    Scanner keyboard = new Scanner(System.in);
    // Rest unchanged
}

【讨论】:

    【解决方案2】:

    您不能动态设置 table1 数组的大小。 确保 a 和 b 小于或等于 raw 和 column。

    (如果您重新创建 table1,我认为您将无法将任何数据放入其中)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-09
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多