Click here to Skip to main content
15,220,234 members
Rate this:
Please Sign up or sign in to vote.
See more:
I create a new 2D array, I get an error. I am new to 2D arrays, so I am not sure what I am supposed to fix.

What I have tried:

I tried adding another pair of brackets, but it did not work.
Here is my code:
`//test to see if the matrix is magic.
public boolean isMagic() { 
 int[][] matrix = new int[][][arraysize];(here)`
 `// loop starts at 0, then loop will go horizontally until it reaches the end of the row. Then it will go to the next column.` 
` for(int i =0; i< arraysize; i++){`
   `for(int x=0; x<arraysize; x++){`
     `matrix[i] +=matrixArray[i][x];`
     
   
`}
}`
 
   
`}
}`
Posted
Updated 25-Apr-20 9:00am
Rate this:
Please Sign up or sign in to vote.

Solution 1

look at your code:
int[][] matrix = new int[][][arraysize];

You are declaring matrix as a two dimensional array of integers, and trying to assign a three dimensional array to it. That won't work, any more that you can fit a quart into a pint pot!
You also need to specify both dimensions of the 2D array when you create the actual instance and assign the space:
int[][] matrix = new int[arraysize][arraysize];


In addition, when you use it you need to reference both dimensions:
matrix[i][somethingHere] += matrixArray[i][x];
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Quote:
Line: 13] error: ']' expected.

Look at your code:
int[][] matrix = new int[][][arraysize];
// ^ here you say you want a 2d array
//                      ^ here you give 3 dimension
...
matrix[i] +=matrixArray[i][x];
//     ^ and here, there is only 1 dimension
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100