I have here a simple Java Program. I am writing this to walk through the logic of the program step by step and verify why it returns the output that it does. I would appreciate any feedback on the way I'm interpreting this.
I'll display the program first, and then explain how it works afterwards.
public class Test9 {
public static void main (String [] args) {
int x = 0;
int y = 10;
for (int z = 0; z < 5; z++) {
if ((y-- > 7) || (++x > 2)) {
y--;
}
}
System.out.println(y + "" + x);
}
}
What is the output and why?
In order to know the correct output of this program, it's necessary to keep a running tally of all three int variables, x, y, and z, during the course of the "for" loop.
At the beginning of the loop, z=0, x=0, and y=10. It then proceeds to the if statement, where it looks to see if the current value of y is greater than 7. It's important to note that y-- means that it will post-decrement y by 1. Which means AFTER the conditional statement has been been decided True or False.
So, since y=10, currently, 10>7, and the statement is True. Since this conditional statement is true and it sees that an OR operator is next, it skips the ++x>2 since it doesn't need to know whether it is TRUE or FALSE. The contents of the loop are now performed, y--, which makes y=8. Decremented once in the conditional statement and once inside the if statement. x remains 0.
The next iteration begins with, z=1, y=8. x=0. The same rules apply, so 8>7, y will be decremented by 2 and x will remain the same.
The third iteration begins with z=2, y=6, x=0. This time around, 6>7 is false, but y is still post decremented. So y=5, and ++x>2, will evaluate as 1>2, since ++x is the prefix version and adds 1 before the operation takes place. Both operations are false, and y will not be decremented a second time.
The forth iteration begins with z=3, y=5, x=1. 5>7 is false, y is decremented to 4. 2>2 is false as well, therefore no 2nd decrement to y.
The fifth iteration begins with z=4, y=4, x=2. 4>7 is false, y is decremented to 3. 3>2 is true! So y will be decremented a 2nd time, to 2.
The ending values are y=2, x=3. Therefore the program output will be: 2 3
It's important to understand when the increments and decrements happen and when开发者_高级运维 they don't, especially when they are inside the conditional statements of an if statement, since it will impact the final output.
If there are terms/jargon, ways of saying things, or flaws in my logic please let me know. I'm trying to understand all the fundamentals of java. Thanks.
You logic is correct... But what is actually the question?
精彩评论