0

ユーザーが編集できる動的な 2D 配列を作成する必要があります。私はさまざまな方法を試しましたが、診断を容易にするために個別に実行しようとしましたが、常に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

考えてみると、次のようになります。

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 に答える
1

もちろん、あなたはArrayIndexOutOfBoundsException. 配列を[0][0]次元で初期化しています。rowsどんな価値観を持っているかを詳しく見てみましょうcols

修理:

n行と列の最大数を許可しmます。
例えばint rows = 5, cols = 6

または、読み取り後に配列の初期化を移動するだけrowsです。colsScanner

怒る:

int rows = Integer.MAX_VALUE;
int cols = Integer.MAX_VALUE;
于 2013-09-23T20:12:06.040 に答える