java – 作业给出了意想不到的答案

前端之家收集整理的这篇文章主要介绍了java – 作业给出了意想不到的答案前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
今天我遇到了以下问题,我似乎找不到一个解决方案:
int i,j,k;

i = j = k = 3;

i = k++;

所以对我而言,变量’i’现在必须具有值4,因为我们将’k’的增量分配给它似乎是合乎逻辑的.在多项选择测试中,第三行之后的正确值代替:

k = 4

i != 4

由于我们将k的增量分配给i,所以给定的解决方案与我预期的完全相反.
提前致谢!

解决方法

首先,如JB Nizet所说,不要这样做.偶尔我会在另一个表达式中使用后缀增量,对于像array [index] = value这样的东西,但是为了清楚起见,我经常会把它分成两个语句.

我不会回答这个问题,但所有答案(在发布时)都犯同样的错误:这不是时间问题;这是表达式k的值的问题.

对i的分配发生在k的增量之后,但是表达式k的值是k的原始值,而不是递增的值.

所以这段代码

i = k++;

相当于:

int tmp = k;
k++;
i = tmp;

section 15.14.2 of the JLS(重点):

[…] Otherwise,the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition,binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary,the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to Boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.

这个差异是非常重要的,可以很容易地看出,如果不使用postfix表达式作为一个赋值,你调用一个方法

public class Test {

    private static int k = 0;

    public static void main(String[] args) throws Exception {
        foo(k++);
    }

    private static void foo(int x) {
        System.out.println("Value of parameter: " + x);
        System.out.println("Value of k: " + k);
    }
}

结果是:

Value of parameter: 0
Value of k: 1

可以看出,在我们称之为方法的时候,k已经增加了,但是传递给该方法的值仍然是原始值.

原文链接:https://www.f2er.com/java/123243.html

猜你在找的Java相关文章