a. The mean of a list of numbers is its arithmetic average. The median of a list
ID: 3729888 • Letter: A
Question
a. The mean of a list of numbers is its arithmetic average. The median of a list is its middle value when the values are placed in order. For example, if a list contains 1, 4, 7, 8, and 10, then the mean is 6 and the median is 7. Write an application that allows you to enter five integers and displays the values, their mean, and their median. Save the files as MeanMedian.java.
b. Revise the MeanMedian class so that the user can enter any number of values up to 20. If the list has an even number of values, the median is the numeric average of the values in the two middle positions. Save the file as MeanMedian2.java.
Explanation / Answer
Answer:
MeanMedian.java:
import java.util.Scanner;
public class MeanMedian {
public static void main(String[] args){
int size = 0; // Size of the series
int temp = 0; // for sorting purpose
int userInut[] = null; // to store user input series
System.out.println("Please Enter total number of integers : ");
Scanner sc = new Scanner(System.in);
size = sc.nextInt();
System.out.println("Please enter the integer list: ");
userInut = new int[size];
// Reading the input from user
for(int i = 0; i< size ; i++){
userInut[i] = sc.nextInt();
}
// Sorting the series entered by user
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (userInut[i] > userInut[j])
{
temp = userInut[i];
userInut[i] = userInut[j];
userInut[j] = temp;
}
}
}
//Printing the array in ascending order
System.out.print("Ascending Order: ");
for (int i = 0; i < size ; i++) {
if(i == size-1){
System.out.print(userInut[i] );
}else {
System.out.print(userInut[i] + ", ");
}
}
// calling calculateMean ,calculateMedian functions and printing the mean and median values
System.out.println(" The Mean of the series is: " + new MeanMedian().calculateMean(userInut, size));
System.out.println("The Median of the series is: " + new MeanMedian().calculateMedian(userInut, size));
}
// Function for calculating Mean
double calculateMean(int a[], int size){
double mean = 0;
for(int i=0; i<size; i++)
{
mean = mean + a[i];
}
mean = (double)mean/size;
return mean;
}
// Function for calculating Median
double calculateMedian(int a[], int size){
double median = 0;
if(size%2 == 0)
{
median = (double)(a[(size/2)-1] + a[size/2])/2;
}
else
{
median = a[size/2] ;
}
return median;
}
}
Output 1:
Please Enter total number of integers :
5
Please enter the integer list:
1
4
7
8
10
Ascending Order: 1, 4, 7, 8, 10
The Mean of the series is: 6.0
The Median of the series is: 7.0
Output 2:
Please Enter total number of integers :
10
Please enter the integer list:
1
4
7
3
8
10
11
16
5
19
Ascending Order: 1, 3, 4, 5, 7, 8, 10, 11, 16, 19
The Mean of the series is: 8.4
The Median of the series is: 7.5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.