SCJP程序输出8 2如何?
问题描述:
class Foozit {
public static void main(String[] args) {
Integer x = 0;
Integer y = 0;
for (Short z = 0; z < 5; z++) {
if ((++x > 2) || ++y > 2)
x++;
}
System.out.println(x + "Hello World!" + y);
}
}
我想这SCJP一段代码和我得到的输出5 3谁能告诉我在哪里,我错了SCJP程序输出8 2如何?
答
循环执行5次(Z从0〜4)
在if条件,++ x全部评估五次。但++ y仅在条件的第一部分为假时才被评估。
即,这种情况:
if ((++x > 2) || ++y > 2)
变为:
//1st iteration
if(1 > 2 || 1 > 2) //False, x++ is not evaluated
//2nd iteration
if(2 > 2 || 2 > 2) //False, x++ is not evaluated
//3rd iteration
if(3 > 2 || 2 > 2) //True, the second ++y is skipped, but x++ is evaluated, x becomes 4
//4th iteration
if(5 > 2 || 2 > 2) //True, the second ++y is skipped, but x++ is evaluated, x becomes 6
//5th iteration
if(7 > 2 || 2 > 2) //True, the second ++y is skipped, but x++ is evaluated, x becomes 8
所以最后,我们有:
x = 8 and y = 2
记住:++ x是预增量(思变并且使用),而x ++是后增量(think use-and-change)
+0
谢谢vaisakh先生一步一步地和OR操作员一起给出预递增和后递增的清楚说明。谢谢你提醒我OR操作员的规则。 – 2012-07-12 06:49:00
+0
谢谢。如果你发现答案有用,你能接受吗? :) – vaisakh 2012-07-13 17:47:19
你是什么意思,“出错了”?它输出它输出的内容 - 有什么问题? – 2012-07-11 13:16:46
我越来越8 2. – 2012-07-11 13:19:31
我也8和2 – yen1k 2012-07-11 13:21:23