Note that there are some explanatory texts on larger screens.

plurals
  1. POerror while trying to get a sum
    text
    copied!<p>I am trying to get the sum of my array called matrix. However when I compile it I receive this error: <code>bad operand types for binary operator '+' first type: int; second type:int[]</code>. I do not understand why this is causing an error. Please help me understand, here is my code:</p> <pre><code>/** Sophia Ali 1. Matrix, getSumMatrix, getSumMatrixDiag: Email just Matrix.java. Write a class called Matrix that contains a private 2-dimensional int array called 'matrix' that can be up to 10 rows by 10 columns maximum. Use two constants MAXROWS=10 and MAXCOLS=10 to construct 'matrix.' The Matrix class will also need the following attributes: private int rows; // number of rows to use in matrix private int cols; // number of cols to use in matrix The rows and cols will contains values that are less than equal to MAXROWS and MAXCOLS. Write a default Matrix class constructor that constructs the 'matrix' array with the following values: {{1,2,4,5},{6,7,8,9},{10,11,12,13}, {14,15,16,17}} The constructor must also set the rows and cols variables to match the above matrix. Write a method 'getSumMatrix' that returns the sum of all the integers in the array 'matrix'. Write a method 'getSumMatrixDiag' that returns the sum of all the integers in the major diagonal of the array 'matrix'. A major diagonal is the diagonal formed from the top left corner to the bottom right corner of the matrix. You do not have to write a TestMatrix class to test the Matrix class. Just use the BlueJ object creation and testing feature. */ public class Matrix { static final int MAXROWS = 10; static final int MAXCOLS = 10; private int rows; private int cols; private int [][] matrix = new int [MAXROWS][MAXCOLS]; public Matrix() { int matrix[][] = { {1, 2, 4, 5}, {6, 7, 8, 9}, {10, 11, 12, 13}, {14, 15, 16, 17}}; getSumMethod(matrix); getSumMatrixDiag(matrix); } public int getSumMethod(int[][] matrix) { int sum = 0; for (int i = 0; i &lt; matrix.length; i++) { sum += matrix[i]; } return sum; } /* int i, result; result = 0; for(i=0; i &lt; matrix.length; i++) { i++; result = result + i; } return result; } */ public int getSumMatrixDiag(int[][] matrix) { int sum = 0; for (int i =0; i&lt; matrix.length; i++) { i++; sum = (int)(sum + matrix[i][i]); } return sum; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload