Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

math

max

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; 

I want to take the three of them and use Math.max() to find the max of the three but if I pass in more then two values then it gives me an error. For instance:

// this gives me an error double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2); 

Please let me know what I'm doing wrong.

like image 895
Drew Bartlett Avatar asked Feb 13 '11 03:02

Drew Bartlett


People also ask

How do you find the maximum of 3 numbers in Java?

First, the three numbers are defined. If num1 is greater than num2 and num3, then it is the maximum number. If num2 is greater than num1 and num3, it is the maximum number. Otherwise, num3 is the maximum number.

How do you find the maximum of multiple numbers in Java?

If you want the maximum of three, use Math. max(MY_INT1, Math. max(MY_INT2, MY_DOUBLE2)) .


2 Answers

Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).

like image 83
Jeremiah Willcock Avatar answered Oct 05 '22 15:10

Jeremiah Willcock


If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.

https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])

NumberUtils.max(int[]) 
like image 28
eugene Avatar answered Oct 05 '22 14:10

eugene