Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write Java program: Write a boolean method that will return true if the sum of t

ID: 3754903 • Letter: W

Question

Write Java program: Write a boolean method that will return true if the sum of the diagonal (upper-left to lower-right) of a two-dimension array is equal to the sum of a given row: diagonalEqualsRow ( int [ ][ ] myArray, int row) If the array is not a square matrix of the row number is out of bounds, throw an IllegalArgumentException with an appropriate message.

For example:

myArray 1

1 3 5 7 9

2 3 4 6 8

0 1 5 1 3

4 5 2 7 8

7 6 3 2 9

myArray2

1 3 3 2

4 2 5 6

1 2 3 4

7 8 9 4

myArray3

1 3 5 6 7

0 8 7 4 3

myArray4

1 3 3 2

4 2 5 6

1 2 3 4

7 8 9 4

diagonalEqualsRow (myArray1, 0) returns true

diagonalEqualsRow (myArray2, 2) returns true

diagonalEqualsRow (myArray3, 0) throw an exception – not a square matrix

diagonalEqualsRow (myArray1, 6) throw an exception – illegal row

Explanation / Answer

ANSWER:

A boolean method that will return true if the sum of the diagonal (upper- left to lower- right) of two - dimenssion array is equal to the sum.

public boolean diagonalEqualsRow(int[][] myArray,int row)
{
int rows=myArray.length;
int cols=myArray[0].length;
int rowsum=0,diagsum=0;
if(rows!=cols)
throw new OutOfBoundsException("not a square matrix");
try
{
if(row>rows)
throw new IllegalArgumentException("Illegal row");
}
catch(Exception e)
{
e.printStackTrace();
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(i==row-1)rowsum+=myArray[i][j];
if(i==j)diagsum+=myArray[i][j];
}
}
if(rowsum==diagsum)return true;
else return false;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote