Page 1 of 1
About Question enthuware.ocajp.i.v7.2.1224
Posted: Tue Feb 14, 2017 8:56 pm
by skissh
Since the if statement cannot change the execution flow could we just replace it with i++; --j; as we think about the loop's execution. I have seen this construction before in loop test questions, where an if statement when true executes continue;. If the if statement is the last line of the loop body then the if conditions result does not matter. Both true and false result in continuing the loop. Is my analysis correct?
Re: About Question enthuware.ocajp.i.v7.2.1224
Posted: Tue Feb 14, 2017 11:21 pm
by admin
I am sorry but I did not understand the scenario you have described. Can you please post some code to show what you mean?
Paul.
Re: About Question enthuware.ocajp.i.v7.2.1224
Posted: Wed Feb 15, 2017 8:23 am
by skissh
My point is that the if statement cannot change the flow of the program regardless of the values of i and j. Once the test taker notices this they should not waste time evaluating whether (i++ < j--) is true or false. The methods in the following code reproduce the function of the code in the test question, one with the if statement and one without. When using the same input for each of the methods they always produce the same result.
Code: Select all
class Main {
public static void main(String[] args) {
withIf(1,10);
withoutIf(1,10);
}
private static void withIf(int i, int j) {
int k =1;
do {
System.out.println("Iteration "+k+": i=" + i + " j=" + j);
k++;
if (i++ > --j) continue;
} while (i < 5);
System.out.println("i=" + i + " j=" + j);
}
private static void withoutIf(int i, int j) {
int k =1;
do {
System.out.println("Iteration "+k+": i=" + i + " j=" + j);
k++;
i++; --j;
} while (i < 5);
System.out.println("i=" + i + " j=" + j);
}
}
Re: About Question enthuware.ocajp.i.v7.2.1224
Posted: Wed Feb 15, 2017 9:03 pm
by admin
Yes, that is correct.