0

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.

Daniel
  • 17
  • 4
  • numbers[rows][columns] = values; => numbers[i][j] = values; – yavuzkavus Apr 08 '17 at 20:27
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Siguza Apr 08 '17 at 21:14

3 Answers3

4

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).

Chris Gong
  • 8,031
  • 4
  • 30
  • 51
1

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.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

In your code here :

numbers[rows][columns] = values;

I believe you meant

numbers[i][j] = values;

Thanks

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
jscriptor
  • 775
  • 1
  • 11
  • 26