Reputation: 23
How do I obtain the max value of both the given int and double values?
package _pasted_code_;
import java.util.Scanner;
public class extra {
public static void main(String[] args) {
double x = 2.0;
double y = 3.0;
double z = 5.67;
int a = 3;
int b = 9;
double answer = max(x, y);
System.out.println("The largest number is: " + answer);
double answer = max(x, y, z);
int max = max(a, b);
}
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static int max (int x, int y) {
if (x > y)
return x;
else
return y;
}
public static double max(double num1, double num2, double num3) {
if ((num1 > num2) && (num1 > num3))
return num1;
else
return num2;
else
return num3;
}
}
Upvotes: 1
Views: 1975
Reputation: 22977
First off, if you just use parameters of type double
, Java will automatically perform a primitive conversion from int
to double
.
Second, you can indeed use Math.max
of compare the two, returning the highest value.
However, if you have many doubles to compare, it will become cumbersome to write Math.max
for each comparison. In that case, I suggest using a stream:
double[] numbers = ...;
double max = Arrays.stream(numbers)
.max()
.get();
Note: this will throw an Exception if the array is empty.
Upvotes: 0
Reputation: 512
The best practice here is to use method overloading
(Assuming that you do not want to use Java's own max/min method). Any method has its own signature and they are uniquely identified with the signatures. So, what I would recommend is defining method as follows:
public static int max(int x, int y) {
// your implementation
}
public static double max(double x, double y) {
// your implementation
}
But remember, it is always better to use Java's min, max methods.
Upvotes: 0
Reputation: 422
Like previously stated, you could use the Math.max method inside your code to receive the max number. same with the Math.min(x,y). They both work the same way.
therefore lets put it in simple terms.
public static double max(double num1, double num2)
{
return Math.Max(num1, num2);
}
also
public static int max (int x, int y)
{
return Math.max(x,y);
}
It's quite simple. I believe someone might've answered it already, but it's the same concept.
Upvotes: 0
Reputation: 4688
You can use Math.max(double a, double b) and Math.max(int a, int b)
Example:
public static int max(int x, int y) {
return Math.max(x, y);
}
public static double max(double num1, double num2) {
return Math.max(num1, num2);
}
public static double max(double num1, double num2, double num3) {
return Math.max(Math.max(num1, num2), num3);
}
Upvotes: 1
Reputation: 500
Java will convert an int
to a double
when needed. Also, just use Java's Math.max()
.
Upvotes: 0