【问题标题】:Explain Code (if statement with arrays)解释代码(带有数组的 if 语句)
【发布时间】:2017-12-29 21:31:45
【问题描述】:

这段代码打印出数组连续两天的最大温度波动。

但我不太明白 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;
            }
        }
    }
}

}

提前致谢。

【问题讨论】:

  • 哪个 if 语句?所有这些?
  • 理解这样的代码的最好方法是用你的调试器单步调试它,并检查每一行之后的所有变量。
  • 第二个和第三个:)
  • 第一个和第二个 if 相当混乱。我会使用绝对差异:newMaxDiff = Math.abs(temperature[i + 1] - temperature[i]);

标签: java arrays if-statement


【解决方案1】:

我添加了一些 cmets - 应该会有所帮助。

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

【讨论】:

    【解决方案2】:

    @OldCurmudgeon 已经回答了这个问题,但也许您可以使用一些额外的 cmets:

    • 可以通过运行循环直到i &lt; temperature.length-1 来消除if ((i + 1) &lt; temperature.length):这样i+1 将始终是数组的有效索引,因此不需要检查
    • 前两个缩进的if-s 处理温度上升和下降,对于这两种变化,它们最后都提供一个正数。 Java 中有一个数学函数,absolute value, Math.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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多