Java recursion question
Here's a section of code from one of my classes:
public void run() {
SomeClass[][] someClassArray = new SomeClass[6][];
someClassArray[0] = new SomeClass[1];
someClassArray[1] = new SomeClass[4];
someClassArray[2] = new SomeClass[16];
someClassArray[3] = new SomeClass[64];
someClassArray[4] = new SomeClass[256];
someClassArray[5] = new SomeClass[1024];
someFunction(0,0);
}
someFunction(int i, int j) {
if(i == 5) {
someClassArray[i][j].flag = test(i,j); // BASE CASE
}
else {
if(someFunction(someClassArray(i+1,j*4))
&& someFunction(someClassArray(i+1,j*4+1))
&& someFunction(someClassArray(i+1,j*4+2))
&& someFunction(someClassArray(i+1,j*4+3)))
someClassArray[i][j].flag = true;
else
someClassArray[i][j].flag = fals开发者_JS百科e;
}
return someClassArray[i][j].flag;
}
class SomeClass {
boolean flag;
// other stuff
}
boolean test(int i, int j) {
// test some property of this coordinate
}
Essentially what I want is to set the flag of one SomeClass object to true only if the four corresponding objects' flags in the next array level are also true. Unfortunately, I seem to be having problems with this:
if(someFunction(someClassArray(i+1,j*4))
&& someFunction(someClassArray(i+1,j*4+1))
&& someFunction(someClassArray(i+1,j*4+2))
&& someFunction(someClassArray(i+1,j*4+3)))
It looks like it's only checking the first condition (I added in a counter so check how many times someFunction is called and it only went up to 6, rather than the 1365 I should be getting); are you not able to do multiple function calls in an if statement in Java? or am I doing it wrong?
(Sorry about the formatting by the way; this is my first time posting here)
The operands &&
and ||
are so called short-circuiting operators. This means the logic they are in will immediately stop executing if the result in known.
In your case, it probably means that the result of the first call to SomeFunction
is false
. Because you only have AND on that line, the result can't possibly be true
anymore and thus your other 3 calls to SomeFunction
don't get executed.
Bottom-line: change the &&
to &
, this won't short-circuit and all call will get executed.
If condition can be short-circuited if its outcome is clear from the first function call.
精彩评论