Find the max of 3 numbers in Java with different data types

前端 未结 12 1937
情深已故
情深已故 2020-12-03 00:33

Say I have the following three constants:

final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
12条回答
  •  旧时难觅i
    2020-12-03 01:19

    if you want to do a simple, it will be like this

    // Fig. 6.3: MaximumFinder.java
    // Programmer-declared method maximum with three double parameters.
    import java.util.Scanner;
    
    public class MaximumFinder
    {
      // obtain three floating-point values and locate the maximum value
      public static void main(String[] args)
      {
        // create Scanner for input from command window
        Scanner input = new Scanner(System.in);
    
        // prompt for and input three floating-point values
        System.out.print(
          "Enter three floating-point values separated by spaces: ");
        double number1 = input.nextDouble(); // read first double
        double number2 = input.nextDouble(); // read second double
        double number3 = input.nextDouble(); // read third double
    
        // determine the maximum value
        double result = maximum(number1, number2, number3);
    
        // display maximum value
        System.out.println("Maximum is: " + result);
      }
    
      // returns the maximum of its three double parameters          
      public static double maximum(double x, double y, double z)     
      {                                                              
        double maximumValue = x; // assume x is the largest to start
    
        // determine whether y is greater than maximumValue         
        if (y > maximumValue)                                       
          maximumValue = y;                                        
    
        // determine whether z is greater than maximumValue         
        if (z > maximumValue)                                       
          maximumValue = z;                                        
    
        return maximumValue;                                        
      }                                                              
    } // end class MaximumFinder
    

    and the output will be something like this

    Enter three floating-point values separated by spaces: 9.35 2.74 5.1
    Maximum is: 9.35
    

    References Java™ How To Program (Early Objects), Tenth Edition

提交回复
热议问题