Home > Mobile >  Finding sum of a row of A 2D array, out of bounds error when column number is greater
Finding sum of a row of A 2D array, out of bounds error when column number is greater

Time:03-23

enter image description hereI know theres a lot of questions like these but I can't seem to find the error in this. I'm trying to find the sum of a row inputed by a user in a 2D Array. The array size is based on the user input.

   //Ask user for number of rows and columns in 2D Array
    System.out.println("Enter Number of Rows");
    int rows = input.nextInt();
    System.out.println("Enter Number if Columns");
    int columns = input.nextInt();

     int[][] array = new int[rows][columns];
    
    //loop through array to set values to random number from 1-100
    for(int i = 0; i < array.length; i  ){
        for(int j = 0; j < array[i].length; j  ){
            array[i][j] = generator.nextInt(100) 1;//sets random numbers to the element of array
            System.out.print(array[i][j] " \t");
        }
        System.out.println();//next row of array
          
    }
       if(userOpt == 5){
            System.out.println("Enter Row Number");//ask user for a row number
            int rowInput = input.nextInt();
            
            //if row input is greater than the size of rows error check
            if(rowInput >= rows){
                System.out.println("Invalid, Out of Range");
            }else{
            int rowSum = rowSum(array, rowInput);//calls rowSum method
            System.out.println("Sun of Chosen Row is: " rowSum);
            }

here's the method for row sum

 public static int rowSum(int[][] array,int rowInput){
    int rowSum = 0;
   
    for(int i = 0; i < array[i].length; i  ){//loops through  length of array
        rowSum = rowSum   array[rowInput][i];//add each element to row Sum
    }
    return(rowSum);
}

The error only comes when the column number entered by the user is greater than the number of rows.

CodePudding user response:

Exception is thrown by

i < array[i].length

as in the 5th iteration you`re doing

i < array[4].length

but array only has 4 rows (0-3). What you probably want is

i < array[0].length

as every row has the same length.

CodePudding user response:

In rowSum(), simply change:

array[i].length

To:

array[rowInput].length

You could also write it as:

public static int rowSum(int[][] array, int rowInput){
    int rowSum = 0;
    int[] row = array[rowInput];
    for(int i : row) {
        rowSum = rowSum   i; //add each element to row Sum
    }
    return rowSum;
}

As every row in the 2D array is simply a 1D array and using the enhanced for loop syntax eliminates that type of error altogether since we don't care about the index positions of the values; we just want to add them up.

Side note: You have validation for rowInput that checks the upper bound:

//if row input is greater than the size of rows error check
if(rowInput >= rows){

This may or may not be "correct" as your prompt does not specify what the first row is. Should the user be using 0 or 1 as the first row? You should make that very clear to the user. If the user is treating 1 as the first row then you need to subtract one from their value so that it gets the correct row from the zero based Array in Java.

Side, side note: What about the lower bound!? Your code that gets the row number is:

int rowInput = input.nextInt();

This will happily accept -1 as input, but will cause your program to crash.

  • Related