Method 1: Return Median Integer Write a method that accepts three integer values
ID: 3543108 • Letter: M
Question
Method 1: Return Median Integer
Write a method that accepts three integer values and returns the median of the three. The method must accept three ints and have the int return type. Note that the median is the middle value.
Method 2: Return Median Double
Write a method that accepts three double values and returns the median of the three. The method must accept three doubles and have the double return type. This method must be overloaded: Therefore, use the same name as the first method.
Method 3: Sort Three Integers
Write a method that accepts three integers and displays them in sorted order (Ascending). The method must accept three ints and have the void return type.
Testing:
Allow the user to enter ints/doubles to test these three methods. You can use the command line or JOptionPane for this. Have each of the above three methods called at least once in your main method. For the first two methods, print the valuebeing returned by the method. Of course, the third method will be printed from within the method itself.
Here is a sample run of the program:
Sample 1:
Enter three integers: 3 5 9
The median value is 5.
Enter three doubles: 9 6 9.9
The median value is 9.0.
Enter three integers: -5 5 0
The sorted output is -5 0 5.
Explanation / Answer
import java.util.Scanner;
public class Median {
public static void sort(int a,int b,int c)
{
if(a>b){
if(b>c){
System.out.println(c+" "+b +" "+a);
}
else
{
if(a>c)
System.out.println(b+" "+c +" "+a);
else
System.out.println(b+" "+a +" "+c);
}}
else
{
if(a>c)
System.out.println(c+" "+a +" "+b);
else
{
if(b>c)
System.out.println(a+" "+c +" "+b);
else
System.out.println(a+" "+b +" "+c);
}
}
}
public static int medianInteger(int a,int b,int c)
{
if(a>b){
if(b>c){
return b;
}
else
{
if(a>c)return c;
else return a;
}}
else
{
if(a>c) return a;
else
{
if(b>c) return c;
else return b;
}
}
}
public static double medianDouble(double a,double b,double c)
{
if(a>b){
if(b>c){
return b;
}
else
{
if(a>c)return c;
else return a;
}}
else
{
if(a>c) return a;
else
{
if(b>c) return c;
else return b;
}
}
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("enter three integers");
int a1=in.nextInt();
int a2=in.nextInt();
int a3=in.nextInt();
System.out.println("the median value is:"+ medianInteger(a1, a2, a3));
System.out.println("Enter three double values");
double b1=in.nextDouble();
double b2=in.nextDouble();
double b3=in.nextDouble();
System.out.println("the median value is:"+ medianDouble(b1, b2, b3));
System.out.println("enter three integers to get sorted output");
int x1=in.nextInt();
int x2=in.nextInt();
int x3=in.nextInt();
sort(x1,x2,x3);
}
}