简体   繁体   English

在条件语句中与 Java 中的增量运算符混淆

[英]Confusion with increment operators in Java in conditional statements

int i = 10;
if(i++ == i)
System.out.println(i + " is good");
else
System.out.println(i + " is bad");

int j = 20;
if(++j == j)
System.out.println(j + " is good");
else
System.out.println(j + " is bad");

So when thinking about the output my thought process went like this:因此,在考虑 output 时,我的思考过程是这样的:

for the first if condition I thought that since its post increment operator, i value will be used first and then increased so it will execute the if condition and increment the value of i therefore printing output 11 is good对于第一个 if 条件,我认为由于它的后增量运算符,i 值将首先使用然后增加,因此它将执行 if 条件并增加 i 的值,因此打印 output 11 是好的

for the second if condition I thought that since tis pre increment operator, i value will be increased first and then used so the else condition will execute and hence print 21 is bad.对于第二个 if 条件,我认为由于 tis pre 自增运算符,i 值将首先增加然后使用,因此 else 条件将执行,因此 print 21 是错误的。

But when checking it comes as 11 is bad and 21 is good但是当检查它时,11 是坏的,21 是好的

Where am I thinking wrong我在哪里想错了

In the first case you're comparing 10 (not yet incremented) to 11 (already post-incremented when evaluating first i++)在第一种情况下,您将 10(尚未递增)与 11(在评估第一个 i++ 时已经后递增)进行比较

In the second case you're comparing 21 (pre incremented) to 21 (post-incremented by earlier evaluation)在第二种情况下,您将 21(预递增)与 21(通过早期评估后递增)进行比较

Your thinking was good, however you're not factoring what happens with second i/j in the equals condition您的想法很好,但是您没有考虑在 equals 条件下第二个 i/j 会发生什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM