如何找到从随机class生成的数组中的最低值?

How to find the lowest value in an array generated from the random class?

我们必须通过一种方法传递数组,该方法获取最高值、最低值和平均值,然后将它们打印出来。

我在获取分配给 minNum 的最低值时遇到问题。

谢谢!

public static void averageMaxMinMethod(double[] arrayOfDoubles){
   
      double maxNum = 0;
      double minNum = 0;
   
      for(int i = 0; i < arrayOfDoubles.length; i++){
      
         if(arrayOfDoubles[i] > maxNum)
            maxNum = arrayOfDoubles[i];
         if(arrayOfDoubles[i] < minNum)// <=== My poor attempt of getting the lowest value
            minNum = arrayOfDoubles[i];
      }
    System.out.println("Highest given double is: " + maxNum);
    System.out.println("Lowest given double is: " + minNum);
   }
   
   public static void main(String[] args) {   
   //1-3: Set up Scanner object to collect user's input on the size of array.
      Scanner keyboard = new Scanner(System.in);
      System.out.println("How many double numerical entries do you have?");
   //4: Declare an array of size sizeOfArray
      int sizeOfArray = keyboard.nextInt();  
   
      //Initialize array
      double[] arrayOfDoubles;
      arrayOfDoubles = new double[sizeOfArray];   
      
      
      
   
      for(int i = 0; i < sizeOfArray; i++){
      //5: Use the Random number Class and walk over the array 
         Random randomNum = new Random();       
         arrayOfDoubles[i] = randomNum.nextDouble(0.0 , 100.0); 
      }
      //6: Invoke SumMethod
      sumMethod(arrayOfDoubles);
      averageMaxMinMethod(arrayOfDoubles);
      
      
   }
  double maxNum = 0;
  double minNum = 0;

这仅在最大数量至少为零且最小值最多为零时有效 - 否则,这些值不会更新。

而是使用数组中的第一个元素,它至少与最小值一样大,并且至少与最大值一样小。

  double maxNum = arrayOfDoubles[0];
  double minNum = arrayOfDoubles[0];

当然,您不需要在第一次循环迭代时比较这些,因此您可以从 1:

开始循环索引
for(int i = 1; i < arrayOfDoubles.length; i++){

其他人已经指出了您在当前实现中所犯的错误,但是您也忘记了计算平均值。您实际上不必编写代码来执行此操作,Java 包括 DoubleSummaryStatistics,它可以为您提供 maxminaverage。喜欢,

public static void averageMaxMinMethod(double[] arrayOfDoubles) {
    DoubleSummaryStatistics dss = DoubleStream.of(arrayOfDoubles).summaryStatistics();
    System.out.println("Highest given double is: " + dss.getMax());
    System.out.println("Lowest given double is: " + dss.getMin());
    System.out.println("Average is: " + dss.getAverage());
}