Reputation: 55
I'm working on a Sudoku program, and i have a boolean function and inside the function, before each return false statement, i have a print statements to show me where it returned false, Right? well my code below managed to return false without printing anything to screen, altho it did manage to print wtf,ayy,wtf, and a final ayy. which also doesnt make sense because ayy is inside a for loop of 9... anyhelp would be awesome.
if (checkBytez() == false){
fieldsPary[a][b] = 0;
fields[a][b] = 0;
count++;
System.out.println("ayy");
if (count > 1)
break;
continue;
}
public boolean checkBytez() {
byte temp = 45;
byte[] arr;
ArrayList<Byte> arr2 = new ArrayList<Byte>();
for (byte i = 0; i < 9; i++) {
System.out.println("wtf");
temp = 0;
arr = refillArr();
arr2 = new ArrayList<Byte>();
for (byte j = 0; j < 9; j++) {
if (fields[i][j] != 0){
temp += fields[i][j];
arr2.add(fields[i][j]);
}
}
if (arr2.size() > 0){
for (byte b:arr)
if (arr2.contains(b) == false){
temp += b;
System.out.println(temp - b + " += " + b);
}
if (temp != 45){
System.out.println("false1");
return false;
}
}
else if (temp != 45){
if (temp != 0)
System.out.println("false2");
return false;
}
}
for (byte i = 0; i < 9; i++) {
temp = 0;
arr = refillArr();
arr2 = new ArrayList<Byte>();
for (byte j = 0; j < 9; j++) {
if (fields[j][i] != 0){
temp += fields[j][i];
arr2.add(fields[j][i]);
}
}
if (arr2.size() > 0){
for (byte b:arr)
if (arr2.contains(b) == false){
temp += b;
}
if (temp != 45){
System.out.println("false1");
return false;
}
}
else if (temp != 45){
if (temp != 0)
System.out.println("false2");
return false;
}
}
return true;
}
how is this possible edit: output: wtf ayy wtf ayy
Upvotes: 0
Views: 272
Reputation: 1499770
The problem is an if
statement without braces:
if (temp != 0)
System.out.println("false2");
return false;
That code is equivalent to:
if (temp != 0) {
System.out.println("false2");
}
return false;
Always use braces for if
statements, to avoid this sort of thing. Formatting the code in your IDE would have given you a hint about this as well, as it would have outdented the return statement.
As an aside, I would also recommend using:
if (!checkBytez())
instead of
if (checkBytez() == false)
... while it doesn't matter in that particular case, avoiding comparing against Boolean literals can prevent mistakes, e.g.:
if (someValue = false)
which is valid code, but performs an assignment instead of a comparison.
Upvotes: 11