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

前端 未结 12 1897
情深已故
情深已故 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 01:25

    Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so

    public static double max(double... n) {
        int i = 0;
        double max = n[i];
    
        while (++i < n.length)
            if (n[i] > max)
                max = n[i];
    
        return max;
    }
    

    In your example, max could be used like this

    final static int MY_INT1 = 25;
    final static int MY_INT2 = -10;
    final static double MY_DOUBLE1 = 15.5;
    
    public static void main(String[] args) {
        double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
    }
    

提交回复
热议问题