1

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();
    }
    }
1
  • 2
    What happens if you chang for (int j = 0; i< matrix.length;j++) to for (int j = 0; j< matrix[i].length;j++)? Commented Oct 9, 2021 at 3:26

1 Answer 1

1
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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.