首页 > 解决方案 > 比预期更多的结果 Java

问题描述

我正在尝试创建一个方法,而不是返回数组的第二个更大的数字。当我返回值时,控制台中会出现 2 个或更多值。我不明白为什么会这样。有人可以帮我理解这一点吗?我做了一种方法来搜索更大的值,所以我可以在返回第二个更大的值上使用它。

public class ThirdMax {

    public static int maxNum (int[] array) { //Returns the bigger value of the array.

        int aux = 0;    //Variable to store the bigger value found and compare it with the rest.
        for (int i = 0; i < array.length; i++) {

            if(array[i] > aux) {    //If the actual value is bigger than the aux
                aux = array[i];     //override the aux value with actual value.
            }
        }
        System.out.println(aux);
        return aux;
    }

    public static int secondMax(int[] array) {  //Returns the second bigger value on the array.
        int valorMax = maxNum(array);   //Store the bigger value on a variable so we can use it later.
        int valorMax2 = 0;              //Variable to store the result.
        int[] auxArray = new int [array.length];                                
        for (int i = 0; i < array.length; i++) {
            if(array[i] == valorMax) {  //When we get to the valorMax, we replace it in the array with a 0.
                array[i] = 0;
                } else {
                    auxArray[i] = array[i];
                }

            valorMax2 = maxNum(auxArray); //Search again the bigger value after the previous one is replaced by 0.
            }
        return valorMax2;
        }

}

在此先感谢您的时间!

标签: javaloops

解决方案


你打电话maxNum(auxArray);多次。他们每个人都打印一个最大值。

因此,您收到了多个结果。

要立即解决它,请删除函数中的打印System.out.println(aux);

并且在您返回之前只执行一个打印功能

System.out.println(valorMax2);
return valorMax2;

但是你的代码看起来不太好。它需要多次改进。

要找到第二大的数字,您只需要像这样循环一次:

public static int secondMax(int[] array) {
   int max = Integer.MIN_VALUE; // Max value
   int secondMax = Integer.MIN_VALUE; // Second max value, its our result

   for (int i = 0; i < array.length; i++) {
      if (array[i] > max) {
        secondMax = max;
        max = array[i];
      } else if (array[i] > secondMax) {
        secondMax = array[i];
      }
   }
   return secondMax;
}

这看起来不错,但不能扩展到找到第 n 个最大数,因为我们的 if 条件将非常复杂。然后你尝试一次找到最大数量:

// Return max number in array which is lower than ceilValue
// Return Integer.MIN_VALUE if no such value found
public static int maxValueBelow(int[] array, int ceilValue) {
   int max = Integer.MIN_VALUE;
   for (int i = 0; i<array.length; i++) {
       if (array[i] < ceilValue && array[i] > max) {
         max = array[i];
       }
   }
   return max;
}

public static int findNthValue(int[] array) {
  int maxValue = maxValueBelow(array, Integer.MAX_VALUE);
  int secondMaxValue = maxValueBelow(array, maxValue);
  int thirdMaxValue = maxValueBelow(array, secondMaxValue);
  // You can improve this function by give it's a second parameter `n`, and use for loop to find the `n-th` max value.
}

推荐阅读