We use if-else structure to check the each possible scenario and return the median accordingly in the middleValue() method. The main is also provided so that you can test the method.
Comments are used to explain the each line.
You may see the output in the attachment.
public class Main
{
public static void main(String[] args) {
//call the method for different scenarios
System.out.println(middleValue(1, 2, 3));
System.out.println(middleValue(1, 3, 2));
System.out.println(middleValue(2, 1, 3));
System.out.println(middleValue(2, 3, 1));
System.out.println(middleValue(3, 1, 2));
System.out.println(middleValue(3, 2, 1));
}
//method that takes three int and returns an int
public static int middleValue(int n1, int n2, int n3) {
//set the median as n1
int median = n1;
//check the situation where the n1 is the highest
//if n2 is greater than n2 -> n1 > n2 > n3
//if not -> n1 > n3 > n2
if(n1 > n2 && n1 > n3){
if(n2 > n3)
median = n2;
else
median = n3;
}
//check the situation where the n2 is the highest
//if n3 is greater than n1 -> n2 > n3 > n1
//if not -> n2 > n1 > n3
//note that we set the median as n1 by default, that is why there is no else part
else if(n2 > n1 && n2 > n3){
if(n3 > n1)
median = n3;
}
//otherwise, n3 is the highest
//if n2 is greater than n1 -> n3 > n2 > n1
//if not -> n3 > n1 > n2
//note that we set the median as n1 by default, that is why there is no else part
else{
if(n2 > n1)
median = n2;
}
return median;
}
}
You may see another if-else question at:
brainly.com/question/13428325