I'm trying to build a method that would get 4 numbers and returns the maximum number of them.
I tried to write this code that gets 4 numbers but this not working:
Input and output:
double a = Math.max(10, 5, 4, 3);
    System.out.println(a);
public static int max(int a, int b, int c, int d) {
    if (a > b && a > c && a > d)
        return a;
    if (b > a && b > c && b > d)
        return b;
    if (c > a && c > b && c > d)
        return c;
    if (d > b && d > c && d > a)
        return d;
}
                I would simplify this by introducing a variable max:
public static int max(int a, int b, int c, int d) {
    int max = a;
    if (b > max)
        max = b;
    if (c > max)
        max = c;
    if (d > max)
        max = d;
     return max;
}
You could also use Math.max, as suggested by fast snail, but since this seems to be homework, I would prefer the algorithmic solution.
Math.max(Math.max(a,b),Math.max(c,d))
                        Try Math.max like below:
return Math.max(Math.max(a, b), Math.max(c, d));
                        You could always use a method like this which will work as you wanted for any number of integers:
public static Integer max(Integer... vals) {
    return new TreeSet<>(Arrays.asList(vals)).last();
}
Call, for example, as:
System.out.println(max(10, 5, 17, 4, 3));
                        public static int max(Integer... vals) {
    return Collections.max(Arrays.asList(vals));
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With