似乎无法使用和if-else语句在for循环中获得正确的值

时间:2014-01-06 19:54:41

标签: java

这是我的代码:

    int numArray [] = {1, 7, 6, 4, 5, 9};

    int high = 0,low = 0;

    for (int count = 0; count < 2; count++) {
        if (count == 0) {
            for (int countA = 0; countA < numArray.length-1; countA++) { //The increment expression is invoked after each iteration/time through the loop.
                high = numArray[countA];
                if (high < numArray[countA+1]) {
                    high = numArray[countA+1];
                }
            }
        }
        else {
            for (int countB = 0; countB < numArray.length-1; countB++) {
                low = numArray[countB];
                if (low > numArray[countB+1]) {
                    low = numArray[countB+1];
                }
            }   
        }
    }

当我从else块打印low值时,它会打印5而不是预期值1.为什么会这样?

3 个答案:

答案 0 :(得分:2)

你可以像这样排序数组(或数组的克隆)

public static void main(String[] args) {
  int numArray [] = {1, 7, 6, 4, 5, 9};
  int [] copy = numArray.clone();
  Arrays.sort(copy);

  int high = copy[copy.length - 1],low = copy[0];
  System.out.printf("Values = %s, Low = %d, High = %d\n", 
      java.util.Arrays.toString(numArray), low, high);
}

哪个输出

Values = [1, 7, 6, 4, 5, 9], Low = 1, High = 9

答案 1 :(得分:1)

我知道它并没有真正回答你的问题,而是代码:

for (int count = 0; count < 2; count++) {
  if (count==0) {
    doSomething();
  } else {
    doSomethingElse();
  }
}

完全相同
doSomething();
doSomethingElse();

始终考虑KISS Principle

答案 2 :(得分:0)

其他响应者给了你一个更好的方法来写这个,但是为了专门解决你原来的问题,你得到一个“意外”(对你)值“低”的原因是你要分配每个条目数组无条件地“低”。带有“5”的条目是您处理的最后一个条目,因此这是您最终得到的值。

要解决此特定问题,您可以将数组条目值分配给一个名为“newlow”的新局部变量。然后,将“newlow”与现有的“low”值进行比较,然后有条件地分配它,或许像这样:

            low = numArray[0];
            for (int countB = 0; countB < numArray.length-1; countB++) {
                int newlow = numArray[countB];
                if (newlow < low) {
                    low = newlow;
                }
            }