Search code examples
javaarraysmethodsbluej

2-dimensional array index out of bounds; creating new 2d array same size as parameter?


I get an error message on this line of code

arraySum [i][j] = array1 [i][j] + array2 [i][j];

and when calling the method class

int [][]sum = doTheMath(array1,array2, '+');

My problem may be in creating the new double array with the same length as the one's in the parameter. For rows I use :6 and for columns I use :4.

 public static int [][]doTheMath(int [][]array1, int [][]array2, char arithmetic)
{
    // Declares 2-dimensional array the same size as one in parameters
    int [][]arraySum = new int [array1.length][array1[0].length];

    for (int i = 0; i < arraySum.length; i++)
        arraySum[i] = new int [array1[i].length];

    // For loop to take each row and column to separately do arithmetic on
    for (int i = 0; i < arraySum.length; i++) {
        for (int j = 0; j < arraySum.length; j++) {
            if (arithmetic == '+') 
                arraySum [i][j] = array1 [i][j] + array2 [i][j];
            else if (arithmetic == '-') 
                arraySum [i][j] = array1 [i][j] - array2 [i][j]; 
            else if (arithmetic == '*') 
                arraySum [i][j] = array1 [i][j] * array2 [i][j];
            else if (arithmetic == '/') 
                arraySum [i][j] = array1 [i][j] / array2 [i][j];
            else if (arithmetic == '%')
                arraySum [i][j] = array1 [i][j] % array2 [i][j];
        }
    }

    // arraySum value is returned
    return arraySum;
}

Array 1 and Array 2 values come from this method class.

public static int getSize(String args)
{
    // Scanner for keyboard input
    Scanner keyboard = new Scanner(System.in);

    // Declares input as integer
    int input = 0;

    // Will print rows or columns and take keyboard input
    System.out.print(args);
    input = keyboard.nextInt();

    // While loop to check if input is in between 2 and 6, if not will print error
    while (input < 2 || input > 6) {
        System.out.print(args);
        input = keyboard.nextInt();
        if (input < 2 || input > 6)
            System.out.println("The number your entered was not between 2 and 6.");
    }

    // Input value is returned
    return input;
}

Solution

  • This part of your code is useless

    for (int i = 0; i < arraySum.length; i++)
        arraySum[i] = new int [array1[i].length];
    

    as this line

    int [][]arraySum = new int [array1.length][array1[0].length];
    

    already set the length of the array1.

    As for your exception, I believe you want to change this line

    for (int j = 0; j < arraySum.length; j++)
    

    to

    for (int j = 0; j < arraySum[i].length; j++)