Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create max method that gets 4 numbers and returns the maximum number?

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;
}
like image 674
YoAv Avatar asked Dec 04 '14 11:12

YoAv


4 Answers

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))
like image 98
Patrick Hofman Avatar answered Oct 12 '22 22:10

Patrick Hofman


Try Math.max like below:

return Math.max(Math.max(a, b), Math.max(c, d));
like image 29
SMA Avatar answered Oct 12 '22 23:10

SMA


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));
like image 29
BarrySW19 Avatar answered Oct 12 '22 22:10

BarrySW19


public static int max(Integer... vals) {
    return Collections.max(Arrays.asList(vals));
}
like image 25
shifu Avatar answered Oct 12 '22 23:10

shifu