package Homeworks;
public class HomeWork85 {
public static void main(String[] args) {
int[][] a = {
{1,1,1,2},
{1,1,1},
{1,1,1}
};
int[][] b = {
{1,1,1,1},
{1,1,1,1},
{1,1,1,1}
};
for (int i=0; i<a.length;i++) {
for (int j=0;j<a[i].length-1;j++) {
if (a.length==a[j].length) {
System.out.println("It is a square");
}else {
System.out.println("Not a square");
}
}
}
}
}
Asked
Active
Viewed 491 times
-2
-
My result: Not a square Not a square Not a square It is a square It is a square It is a square It is a square – ozz Feb 25 '20 at 00:53
-
1...And the question is ? – John3136 Feb 25 '20 at 00:59
-
It doesn't give me a single "its a square" or its not a square. it gives me both it is a square and its not a square. So i do not know what im doing wrong. – ozz Feb 25 '20 at 04:36
1 Answers
0
Although your logic is correct, you are doing redundant checking. What you should ideally do is you have the row length using a.length
. You should iterate through each row once, using a[j].length
and check whether the number of rows is equal to the number of values in each row(number of columns).
If not, then print 'not a square' and break out of the loop. Keep a flag indicating that the loop was stopped explicitly. If not, the flag remains the same and you can conclude that it was a square.
int flag = 0;
for (int j=0;j<a.length;j++) {
if (a.length != a[j].length){
System.out.println("Not a Square!");
flag = 1;
break;
}
}
if (flag == 0){
System.out.println("It is a Square");
}

Boby Robert
- 84
- 3
-
thank you for this. why are you making flag=1 and flag==0? What do these numbers represent? – ozz Feb 25 '20 at 17:56
-
Flag, in general, is an indicator of whether an event has occurred or not. In this case, there can be two outcomes, either its a square or it's not. So in my for loop, I'm checking whether there is any mismatch between rows and column length (Not a square). So if this event occurs I set some value to flag (1). If the value is 1, It means a decision has already been made that its not a square and I do not need to process further. I just used 1 and 0 for convenience, it can be any number or boolean as well. – Boby Robert Feb 28 '20 at 04:56