Java 2d array, test for square

Go To StackoverFlow.com

1

This is a myprogramminglab problem. I'm given an array (a2d) and I need to determine if every row and column has the same number of elements as every other row and column. If it is then I set the boolean isSquare to true.

I have come up with the following code, but it doesn't like it and it isn't giving me any suggestions on how to improve it.

for(int row = 0; row < a2d.length; row++){
for(int col = 0; col < a2d[row].length; col++)
    if(a2d.length == a2d[row].length)
        isSquare = true;
    else
        isSquare = false;
}

Am I testing this the wrong way or is there a better way?

Thanks

2012-04-05 01:42
by Jimmy_barnes


5

There is no need for 2 loops you should be able to do something like this (I'm not going to give the code since it's homework)

1. Save the length of the array (a2d.length)
2. Loop over all the rows
3. Check to see if the given row has the same length
4. if Not return false 
5. if you reach the end of the loop return true
2012-04-05 01:51
by twain249
see my code above for the implementation - Jeffrey Blattman 2012-04-05 01:55
Thanks to everyone for the help. I preferred this style of answer - Jimmy_barnes 2012-04-05 02:49


1

for (int i = 0, l = a2d.length; i < l; i++) {
  if (a2d[i].length != l) {
    return false;
  }
}
return true;

you just need to ensure that all of the lengths of the 2nd dimension arrays are the same length as the first dimension array.

2012-04-05 01:51
by Jeffrey Blattman
This is the correct answer (so is the accepted answer by twain249). I can't understand who and why voted this one down - Male 2017-07-29 19:08


0

if(a2d.length == a2d[row].length)
    isSquare = true;
else
    isSquare = false;

If the last element passes this will return true always. Try this:

isSquare = true;
for(int row = 0; row < a2d.length; row++){
for(int col = 0; col < a2d[row].length; col++)
    if(a2d.length != a2d[row].length)
        isSquare = false;
}
2012-04-05 01:50
by RyanS
There is no need to loop over every column it doesn't change the if statemen - twain249 2012-04-05 02:00
I think that was the main issue, it was returning true when not all the elements passed - Jimmy_barnes 2012-04-05 02:36
Ads