I hava a problem, when I tried to enter random numbers (0 and 1) in a 2D array, that when I enter a number of rows and columns, the output will appear Exception in thread.
"main":java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds
for length 3
at Test.main
public static void main(String[] args) {
Random r = new Random();
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows");
int row = input.nextInt();
System.out.println("Enter number of columns");
int column = input.nextInt();
int matrix [][] = new int[row][column];
for(int i = 0; i< matrix.length;i ){
for (int j = 0; i< matrix.length;j ) {
matrix[i][j] = r.nextInt(2);
System.out.print(matrix[i][j] " ");
}
System.out.println();
}
}
CodePudding user response:
import java.util.Random;
import java.util.Scanner;
public class xxxx {
public static void main(String[] args) {
Random r = new Random();
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows");
int row = input.nextInt();
System.out.println("Enter number of columns");
int column = input.nextInt();
int matrix [][] = new int[row][column];
for(int i = 0; i< matrix.length;i ){
for (int j = 0; j< matrix[i].length;j ) {
matrix[i][j] = r.nextInt(2);
System.out.print(matrix[i][j] " ");
}
System.out.println();
}
}
}