Java SCJP程序如何给出输出8 2? class Foozit{ 公共静态void main(字符串[]args){ 整数x=0; 整数y=0; 用于(短z=0;z2)|++y>2) x++; } System.out.println(x+“Hello World!”+y); } }

Java SCJP程序如何给出输出8 2? class Foozit{ 公共静态void main(字符串[]args){ 整数x=0; 整数y=0; 用于(短z=0;z2)|++y>2) x++; } System.out.println(x+“Hello World!”+y); } },java,scjp,post-increment,pre-increment,Java,Scjp,Post Increment,Pre Increment,我尝试了这段scjp代码,得到了输出5 3有人能告诉我哪里出了问题吗循环执行了5次(z从0到4) 在if条件下,++x将全部计算五次。但是,只有当条件的第一部分为false时才计算++y i、 例如,这种情况: class Foozit { public static void main(String[] args) { Integer x = 0; Integer y = 0; for (Short z = 0; z < 5; z+

我尝试了这段scjp代码,得到了输出5 3有人能告诉我哪里出了问题吗

循环执行了5次(z从0到4)

在if条件下,++x将全部计算五次。但是,只有当条件的第一部分为false时才计算++y

i、 例如,这种情况:

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);
    }
}
变成:

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是增量前(考虑更改和使用),而x++是增量后(考虑使用和更改)

循环执行5次(z从0到4)

在if条件下,++x将全部计算五次。但是,只有当条件的第一部分为false时才计算++y

i、 例如,这种情况:

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);
    }
}
变成:

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是增量前(考虑更改和使用),而x++是增量后(考虑使用和更改)

你说的“出错”是什么意思?它输出它输出的东西--问题是什么?我认为OP的问题是“试运行这个程序并确定它的输出”OP得到5 3,不知道为什么程序实际上输出8 2。所有这些都向我证明了SCJP是一种挫折和徒劳的练习。这个问题有什么实际意义?如果我在producton代码中看到了这一点,我一定会绞死那个开发人员。你说“出错”是什么意思?它输出它输出的东西--问题是什么?我认为OP的问题是“试运行这个程序并确定它的输出”OP得到5 3,不知道为什么程序实际上输出8 2。所有这些都向我证明了SCJP是一种挫折和徒劳的练习。这个问题有什么实际意义?如果我在producton代码中看到这一点,我一定要让开发人员知道。感谢vaisakh先生对增量前和增量后以及每一步的流程和OR运算符给出了清晰的解释。感谢你提醒我OR运算符的规则。谢谢。如果你觉得这个答案有用,你能接受吗?:)感谢vaisakh先生对增量前和增量后以及每个流程的步骤和OR运算符进行了清晰的解释。感谢您提醒我OR运算符的规则。谢谢。如果你觉得这个答案有用,你能接受吗?:)