解释代码(if语句与数组)

时间:2017-07-24 10:27:51

标签: java arrays if-statement

此代码连续两天打印出阵列的最大温度波动。

但我真的不明白,if语句会发生什么。

有人请你这么好解释一下吗?

public class NurTests {

public static void main(String[] args) {

    int[] temperature = { 12, 14, 9, 12, 15, 16, 15, 15, 11, 8, 13, 13, 15, 12 };

    int maxTempDiff = 0;
    int foundDay = 0;
    for (int i = 0; i < temperature.length; i++) {
        int newMaxDiff = 0;
        if ((i + 1) < temperature.length) {
            if (temperature[i] < temperature[i + 1]) {
                newMaxDiff = temperature[i + 1] - temperature[i];
            }
            if (temperature[i] >= temperature[i + 1]) {
                newMaxDiff = temperature[i] - temperature[i + 1];
            }
            if (maxTempDiff < newMaxDiff) {
                maxTempDiff = newMaxDiff;
                foundDay = i;
            }
        }
    }
}

}

提前致谢。

2 个答案:

答案 0 :(得分:3)

我添加了一些评论 - 应该有所帮助。

        // Make sure we don't access beyond the length of the array.
        if ((i + 1) < temperature.length) {
            // Is this temp less than the next one?
            if (temperature[i] < temperature[i + 1]) {
                // New max diff is next minus this.
                newMaxDiff = temperature[i + 1] - temperature[i];
            }
            // Is this temp greater than or equal to the next one?
            if (temperature[i] >= temperature[i + 1]) {
                // New max diff is this minus next.
                newMaxDiff = temperature[i] - temperature[i + 1];
            }
            // Is the new temp diff the greatest so far?
            if (maxTempDiff < newMaxDiff) {
                maxTempDiff = newMaxDiff;
                foundDay = i;
            }
        }

答案 1 :(得分:2)

@OldCurmudgeon已经回答了这个问题,但也许您可以使用其他一些评论:

  • if ((i + 1) < temperature.length)可以通过循环运行直到i < temperature.length-1来消除:这种方式i+1将一直是数组的有效索引,因此不需要检查
  • 前两个缩进if - s处理温度上升和下降,并且对于这两种变化,它们在最后提供正数。 Java中有absolute valueMath.abs的数学函数。

结合在一起:

for (int i = 0; i < temperature.length - 1; i++) {
    int newMaxDiff = Math.abs(temperature[i] - temperature[i + 1]);
    if (maxTempDiff < newMaxDiff) {
        maxTempDiff = newMaxDiff;
        foundDay = i;
    }
}