Daniel
Daniel

Reputation: 15

java.lang.ArrayIndexOutOfBoundsException when filling 2d array with user input

This is the code I have currentlly.

public static void testClosestToMean() {

    Scanner input = new Scanner(System.in);
    System.out.println("How many rows does your array have: ");
    int rows = input.nextInt();
    System.out.println("How many columns does your array have: ");
    int columns = input.nextInt();

    double[][] numbers = new double[rows][columns];


    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            System.out.println("Enter a value for your array: ");
            double values = input.nextDouble();
            numbers[rows][columns] = values;
        }
    }
}

When I run my program I reach System.out.println("Enter a value for your array: "); however when I input a single number and press enter this error occurs:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

I'm just generally stuck and would like guidance or even an explanation of why this error keeps occurring.

Upvotes: -1

Views: 1031

Answers (3)

jscriptor
jscriptor

Reputation: 845

In your code here :

numbers[rows][columns] = values;

I believe you meant

numbers[i][j] = values;

Thanks

Upvotes: 0

Ashland Simpson
Ashland Simpson

Reputation: 49

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException means you are exceeding the elements. Please be aware that 0 can also be an item in an array.

For example:

array[0] = "Hey";
array[1] = "Sup! wow... just wow";

If I did

system.out.println(array[2]);

It would print the error

But if i did

system.out.println(array[0], array[1]);

It would work.

Upvotes: 1

Chris Gong
Chris Gong

Reputation: 8229

The indices of your 2D array run from 0 to row-1 for the rows and 0 to columns-1 for the columns. However, you'r trying to access numbers[rows][columns] which is known as an "off-by-one error" because your accessing indices that are each one more than the max possible index. If you want to fix this, then replace rows with i and columns with j like so,

for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns; j++)
    {
        System.out.println("Enter a value for your array: ");
        double values = input.nextDouble();
        numbers[i][j] = values;
    }
}

This way, you're adding entries into your 2D array by filling each row starting from the first row (at index 0) until you reach the last row (at index i-1). And while you're filling each row, you start filling the columns one by one by starting at the first column (at index 0) until you reach the last column (at index j-1).

Upvotes: 4

Related Questions