In: Computer Science
Complete the following method to return the median of three integers. Remember, you need to use the names of the parameters as given in the method header. This is a return method, so you need to include return statement(s) NOT System.out.println.
JAVA PROGRAM
Exampe:
Method call | Value returned |
medof | 5 |
medof | 5 |
medof | -2 |
medof | 0 |
Method header:
public static int medof(int n1,int n2, int n3)
code in java
(code to copy)
public class Main {
public static int medof(int n1, int n2, int n3) {
// check if n2 is the median
if ((n1 < n2 && n2 < n3) || (n3 < n2 && n2 < n1))
return n2;
// Checking for n1
else if ((n2 < n1 && n1 < n3) || (n3 < n1 && n1 < n2))
return n1;
else
return n3;
}
public static void main(String[] args) {
// test the medof function
System.out.println("Method call Value returned");
System.out.println("medof (20, 1, 5) " + medof(20, 1, 5));
System.out.println("medof (5, 3, 1) " + medof(5, 3, 1));
System.out.println("medof (-10, -2, 4) " + medof(-10, -2, 4));
System.out.println("medof (-1, 4, 0) " + medof(-1, 4, 0));
}
}
code screenshot
Sample output screenshot