= + Java中的运算符 [英] =+ Operator in Java

查看:56
本文介绍了= + Java中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

long val = 0;
for(int i = 0; i < 2; val++)
    val =+ ++i;

System.out.println(val);

val = 3到底为什么?

Why is val = 3 in the end?

我会这样计算:

val     i
0       0   i < 2 = true;
0       0   ++i;
0       1   val =+ 1;
1       1   (end of for loop) val++;
2       1   i < 2 = true;
2       1   ++i;
2       2   val =+ 2;
4       2   (end of for loop) val++;
5       2   i < 2 = false;
Output: 5

但是它是3.我不明白为什么当i = 1并预先增加到i = 2时第二次不增加val =+ ++i.

But it's 3. I don't understand why the increment val =+ ++i is not done the second time when i = 1 and getting pre-incremented to i = 2.

推荐答案

让我们首先关注看起来异常的行:

Let's focus on the unusual-looking line first:

val =+ ++i;

此处的运算符为=(分配),+(一元加号)和++(预递增).没有=+运算符. Java将其解释为两个运算符:=+.添加适当的空格会更清楚:

The operators here are = (assignment), + (unary plus), and ++ (pre-increment). There is no =+ operator. Java interprets it as two operators: = and +. It's clearer with appropriate whitespace added:

val = + ++i;

现在让我们分析一下处理过程:

Now let's analyze the processing:

第一次迭代:vali0. i预先增加到1,这是++i的结果.一元+不执行任何操作,并且1被分配给val.然后出现迭代语句val++,现在val2. i仍然是1,因此满足了for循环条件并发生了第二次迭代.

First iteration: val and i are 0. i is pre-incremented to 1, and that's the result of ++i. The unary + does nothing, and 1 is assigned to val. Then the iteration statement val++ occurs and now val is 2. i is still 1, so the for loop condition is met and a second iteration occurs.

第二次迭代:i再次被预增加到2.一元+不执行任何操作,并且val被分配了2.迭代语句val++再次出现,现在为3.但是i现在是2,并且不小于2,因此for循环终止,并显示val-3-.

Second iteration: i is pre-incremented again, to 2. The unary + does nothing and val is assigned 2. The iteration statement val++ occurs again and it's now 3. But i is now 2, and it's not less than 2, so the for loop terminates, and val -- 3- is printed.

这篇关于= + Java中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆