嵌套数组引用

我目前正在在线学习 Java,对以下代码以及数组中的元素之一的计算结果感到困惑:


int[] a = new int[]{9, 8, 3, 1, 5, 4};


for (int i = 0; i < a.length; i++) {

    if (a[i] % 2 == 0) {

        a[i] += 1;

    } else if (a[i] < a.length) {

        a[i] += a[a[i]];

    }

}

我正在查看a[3]计算结果的数字,当我调试代码时,我的 IDE 显示a[a[i]]计算结果为9,这就是我有点困惑的地方。


我以为a[3]先等于1然后a[1]等于8,但事实似乎并非如此。任何人都可以澄清一下,因为 JetBrains Academy 课程没有提及这一点。


FFIVE
浏览 103回答 3
3回答

拉风的咖菲猫

注意第一个条件 -if (a[i] % 2 == 0) {a[i] += 1;}这会导致偶数值增加。因此a[1]从8增加到9。现在,当i==3,a[a[i]]被评估为a[1]等于 时9。然后将其添加到 的原始值a[3](注意运算符是+=,而不是=),因此a[3]变为1 + 9,即10。

米琪卡哇伊

int[] a = new int[] {9, 8, 3, 1, 5, 4};for (int i = 0; i < a.length; i++){&nbsp; &nbsp; if (a[i] % 2 == 0)&nbsp; &nbsp; &nbsp; &nbsp; a[i] += 1;&nbsp; &nbsp; else if(a[i] < a.length)&nbsp; &nbsp; &nbsp; &nbsp; a[i] += a[a[i]];}|i | a[i] old | a[i] % 2 | a[i] < a.length | a[a[i]] | a[i] new ||--|----------|----------|-----------------|---------|----------||0 |&nbsp; 9&nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; -&nbsp; &nbsp; &nbsp;|&nbsp; &nbsp;-&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; NaN&nbsp; &nbsp; |&nbsp; &nbsp; 9&nbsp; &nbsp; &nbsp;||1 |&nbsp; 8&nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; +&nbsp; &nbsp; &nbsp;|&nbsp; &nbsp;-&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; NaN&nbsp; &nbsp; |&nbsp; &nbsp; 9&nbsp; &nbsp; &nbsp;||2 |&nbsp; 3&nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; -&nbsp; &nbsp; &nbsp;|&nbsp; &nbsp;+&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; 1&nbsp; &nbsp; &nbsp; |&nbsp; &nbsp; 4&nbsp; &nbsp; &nbsp;||3 |&nbsp; 1&nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; -&nbsp; &nbsp; &nbsp;|&nbsp; &nbsp;+&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; 9&nbsp; &nbsp; &nbsp; |&nbsp; &nbsp; 10&nbsp; &nbsp; ||4 |&nbsp; 5&nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; -&nbsp; &nbsp; &nbsp;|&nbsp; &nbsp;+&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; 4&nbsp; &nbsp; &nbsp; |&nbsp; &nbsp; 9&nbsp; &nbsp; &nbsp;||5 |&nbsp; 4&nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; &nbsp; +&nbsp; &nbsp; &nbsp;|&nbsp; &nbsp;-&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;|&nbsp; 9&nbsp; &nbsp; &nbsp; |&nbsp; &nbsp; 5&nbsp; &nbsp; &nbsp;|// a = {9, 9, 4, 10, 9, 5};我以为这a[3]等于1这是正确的,在步骤3,a[3] = 1然后就a[1]等于8这是不正确的,因为在步骤中1它被增加到9

繁星coding

没关系。查看您正在做什么的最佳方法是debuggin(在本例中绘制)您的代码:int[] a = new int[] {9, 8, 3, 1, 5, 4};&nbsp; &nbsp; for (int i = 0; i < a.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; if (a[i] % 2 == 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf(a[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[i] += 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf(a[i]);&nbsp; &nbsp; &nbsp; &nbsp; }else if(a[i] < a.length){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf(a[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; a[i] += a[a[i]];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf(a[i]);}你会看得更清楚。有时,我们自己面对墙壁会更好,因为最好的做法之一就是了解你。祝你好运!。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java