YoAv - 5 months ago 32

Java Question

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;

}

Answer

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(Math.max(a,b),Math.max(c,d)))
```