Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

java - How to find maximum value of set of variables

I was wondering if anyone could help me find the maximum value of a set of variables and assign them to another variable. Here is a snippet of my code that may help with understanding what I am talking about.

// 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 + ".");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Java, you can use Math.max like this:

double maxStock = Math.max( firstQuarter, Math.max( secondQuarter, Math.max( thirdQuarter, fourthQuarter ) ) );

Not the most elegant, but it will work.

Alternatively, for a more robust solution define the following function:

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

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

   return max;
}

Which you can then call by:

double maxStock = findMax(firstQuarter, secondQuarter, thirdQuarter, fourthQuarter);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...