使用if else的Java 2d数组

时间:2016-03-18 15:04:29

标签: java multidimensional-array

我试图在这个2d数组中找到最小值和最大值。我得到正确的输出,(-10作为最小值,40作为最大值)但我似乎无法通过第二次测试,这是{73,0}任何想法?

public class ArraysKeyValue {
   public static void main (String [] args) {
  final int NUM_ROWS = 2;
  final int NUM_COLS = 2;
  int [][] milesTracker = new int[NUM_ROWS][NUM_COLS];
  int i = 0;        
  int j = 0;
  int maxMiles = 0; // Assign with first element in milesTracker before loop
  int minMiles = 0; // Assign with first element in milesTracker before loop

  milesTracker[0][0] = -10;
  milesTracker[0][1] = 20;
  milesTracker[1][0] = 30;
  milesTracker[1][1] = 40;

  maxMiles = milesTracker[1][1];
  minMiles = milesTracker[0][0];

  for (i = 0; i < NUM_ROWS; i++) {
      for (j = 0; j < NUM_COLS; j++) {
          if (i == 0 && j == 0) {
              minMiles = milesTracker[i][j];
              maxMiles = milesTracker[i][j];
          }
         if (milesTracker[i][j] > maxMiles){
                  maxMiles = milesTracker[i][j];
          }
      }
  }

  System.out.println("Min miles: " + minMiles);
  System.out.println("Max miles: " + maxMiles);

} }

3 个答案:

答案 0 :(得分:2)

您似乎忘了相应地调整minMiles。添加另一个if

 if (milesTracker[i][j] < minMiles){
      minMiles = milesTracker[i][j];
 }

答案 1 :(得分:1)

请相应更新您的代码,

.....

 for (j = 0; j < NUM_COLS; j++) {
          if (i == 0 && j == 0) {
              minMiles = milesTracker[i][j];
              maxMiles = milesTracker[i][j];
          }
         if (milesTracker[i][j] > maxMiles){
                  maxMiles = milesTracker[i][j];
          }else if(milesTracker[i][j] < minMiles ){
                    minMiles = milesTracker[i][j];
          }

      }

.....

答案 2 :(得分:0)

如果清理你的代码:

minMiles = maxMiles = milesTracker[0][0];  //init min and max as index = 0
for (i = 1; i < NUM_ROWS; i++) {  //start from index = 1
    for (j = 1; j < NUM_COLS; j++) {
        if (milesTracker[i][j] > maxMiles) {
            maxMiles = milesTracker[i][j];
        }
        else if (milesTracker[i][j] < minMiles) {
            minMiles = milesTracker[i][j];
        }
    }
}