java - 解释代码(带有数组的 if 语句)

标签 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;
            }
        }
    }
}

}

提前致谢。

最佳答案

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

        // 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;
            }
        }

关于java - 解释代码(带有数组的 if 语句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45278176/

相关文章:

PHP 运算符 if 语句 'and' 和 'or'

java - 虚拟键盘上方的 PopupWindow

java - 当我尝试重新定义变量时,出现索引越界错误

java - 打开.jar时为"A java exception has occurred"

java - 使用多个类时输出奇怪

Python - 在曲线函数上方返回数组中的元素数

c - NULL 检查单个 if 语句中的嵌套指针

java - 嵌入实体的自动ID

python - 集成 ODE 后打印数组中的特定值

JavaScript:仅当数组中的所有项目都为真时才执行函数?