如何找到变量集的最大值

Cod*_*y B 13 java variables max

我想知道是否有人可以帮我找到一组变量的最大值并将它们分配给另一个变量.这是我的代码片段,可能有助于理解我在说什么.

// Ask for quarter values.
    System.out.println("What is the value of the first quarter?");
    firstQuarter = input.nextDouble();

    System.out.println("What is the value of the second quarter?");
    secondQuarter = input.nextDouble();

    System.out.println("What is the value of the third quarter?");
    thirdQuarter = input.nextDouble();

    System.out.println("What is the value of the fourth quarter?");
    fourthQuarter = input.nextDouble();

    //Tell client the maximum value/price of the stock during the year.     
    //maxStock = This is where I need help 
    System.out.println("The maximum price of a stock share in the year is: $" + maxStock + ".");
Run Code Online (Sandbox Code Playgroud)

nyb*_*ler 24

在Java中,您可以像这样使用Math.max:

double maxStock = Math.max( firstQuarter, Math.max( secondQuarter, Math.max( thirdQuarter, fourthQuarter ) ) );
Run Code Online (Sandbox Code Playgroud)

不是最优雅的,但它会起作用.

或者,对于更强大的解决方案,定义以下功能:

private double findMax(double... vals) {
   double max = Double.NEGATIVE_INFINITY;

   for (double d : vals) {
      if (d > max) max = d;
   }

   return max;
}
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式致电:

double maxStock = findMax(firstQuarter, secondQuarter, thirdQuarter, fourthQuarter);
Run Code Online (Sandbox Code Playgroud)