Search code examples
javamultidimensional-arraydiagonal

Create a 2D array with first number being the number of rows


1.Create a square 2D array of a size that is decided by user input - the first number being the number of rows. 2.Allow the user to fill the array with integers of their choice. 3. Print to the screen the sum of the diagonals. For example see below

Example 2D Array:

|  1  2  3  4 |
|  5  4  6  9 |
| 11 13 16  6 |
|  2  4 18 20 |

Diagonal 1 = 1, 4, 16, 20. Diagonal 2 = 4, 6, 13, 2. The sum of Diagonal 1 is 41. (1 + 4 + 16 + 20) The sum of Diagonal 2 is 25. (4 + 6 + 13 + 2) The sum of both diagonals is 66. You would return 66, the sum of both diagonals only.

The code I have written is as follows but it is missing the following :

I know I need to fill the array somewhere - but not sure where ??? when I run the sum diagonals it doesn't let me fill array properly ??

import java.util.Scanner;
public class SumOfDiagonals{
    public static void main(String [] args){
        Scanner input = new Scanner (System.in);
        int [][] matrix;
        System.out.print ("Enter row number:");
        int row = input.nextInt();
        int col = row;
        matrix = new int [row][col];
        for (int i=0; i<matrix.length; i++){
            for (int j = 0; i<matrix[0].length; j++){
                System.out.print ("Enter a number for ( "+i+", "+j+")");
                matrix[i][j]=input.nextInt();
            }
        }
        int sum1=0;
        int sum2=0;
        for (int i=0;i<matrix.length;i++){
            sum1 += matrix[i][i];
            sum2 += matrix[i][matrix.length-1-i];
            }
            System.out.println ("Diagonal 1: "+sum1);
            System.out.println ("Diagonal 2: "+sum2);
            System.out.println ("Sum of two diagonals: " + (sum2+sum1));
        }
    }

My error when the test code is as follows:

Your program tested with: 5 5 4 3 2 1 1 2 3 7 5 1 1 1 1 1 11 12 13 14 15 15 14 13 12 11

Your answer: Enter row number:Enter a number for ( 0, 0) Enter a number for ( 0, 1) Enter a number for ( 0, 2) Enter a number for ( 0, 3) Enter a number for ( 0, 4) Enter a number for ( 0, 5) Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at SumOfDiagonals.main(SumOfDiagonals.java:13)

Expected answer: Sum of diagonals = 69

You got a grade of 52


Solution

  • You have a typo in your second for-loop.

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; *HERE* i < matrix[0].length; j++) {
                System.out.print("Enter a number for ( " + i + ", " + j + ")");
                matrix[i][j] = input.nextInt();
            }
        }
    

    should be

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.print("Enter a number for ( " + i + ", " + j + ")");
                matrix[i][j] = input.nextInt();
            }
        }