Skip to content
Advertisement

Creating user input for randomized 2D java array issue – OutOfBoundsException

Trying to create a 2D array that takes the users input for rows and columns. The numbers inside the array are then randomized from 0 to 100. I am getting the following error:

Enter rows for the array: 3

Enter columns for the array: 2

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at test2.main(test2.java:17)

Here is my code:

import java.lang.Math;
import java.util.Scanner;

public class test2 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter rows for the array: ");
        int rows = scan.nextInt();
        System.out.print("Enter columns for the array: ");
        int columns = scan.nextInt();

        int [][] myArray = new int [rows][columns];

        for (rows = 0; rows < myArray.length;rows++) {
            for (columns = 0; columns < myArray.length; columns++)
            myArray[rows][columns] = (int) (Math.random()*100);
            System.out.print(myArray[rows][columns] + "t");
        }
    }
}

Advertisement

Answer

You should use separate variables to run the loops.

public class Random {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter rows for the array: ");
    int rows = scan.nextInt();
    System.out.print("Enter columns for the array: ");
    int columns = scan.nextInt();

    int[][] myArray = new int[rows][columns];

    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < columns; col++) {
            myArray[row][col] = (int) (Math.random() * 100);
            System.out.print(myArray[row][col] + "t");
        }
    }
}

}

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement