Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Java Programming 8th edition chapter 9 #2-part b(MeanMedian2). How do I fix t

ID: 3853603 • Letter: I

Question

In Java Programming 8th edition chapter 9 #2-part b(MeanMedian2). How do I fix the following?

L50: median=(list[m]+list[m-1])/2;

I also had median=(double)(list[m]+list[m-1])/2;

My professor still says………..

I still don't see any type conversion here. If you don't like a type conversion. You can use this way: change a constant 2 to a double 2.0. So, 2 ==> 2.0 (This is a convenient way to avoid an integer division).

I have never done a programming class and I still don’t understand what to fix. Please help!

Explanation / Answer

median=(list[m]+list[m-1])/2;

In the above expression, the array "list" is of the type integer, So both numerator and denominator of type integer, which will return an integer value only.

Also like maths, integers don't take fractions or decimal values. For that, we use either double or float.

Java supports Type promotion, which means, that in an expression, java promotes the type of all the operands to that of the variable with the highest type. For example:

byte a = 225;

byte b = 525;

int c = 45

int d = a + b + c;

In the above expression both a and b are of type byte, but c is of type int, which is the greatest in the expression. So Java promotes the data type of both a and b to int.

If you want to explicitly typecast a result to a target type, you just need to add the keyword of that type in front of that result. For example:

double b = 4.6;

int a = (int) b;

In the above example, the value of b is type cast to an integer. so the value assigned to a will be 4 and not 4.6.

So,here, median=(double)(list[m]+list[m-1])/2;// casting the type of result obtained by (list[m]+list[m-1]) to double.

So the correct code will be:

import java.util.Arrays;

import java.util.Scanner;
public class MeanMedian2
{
public static void main(String[] args)
{
int list[] = new int[20];
int t,x,n=0;
double mean=0, median=0;


Scanner sc=new Scanner(System.in);
System.out.println("Please enter max of 20 numbers or NAN to exit");
try
{
for(int i=0;i<20;i++)
{
x=sc.nextInt();

list[i]=x;
n++;
}
}
catch(Exception e)
{
System.out.println("Thanks for the input");
}   
for(int i=0;i<n;i++)
{
mean = mean+list[i];
}
mean = mean/n;
  
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(list[i]>list[j])
{
t=list[i];
list[i]=list[j];
list[j]=t;
}
}
}
int m=n/2;
if(n%2==0)
{

median=(double)(list[m]+list[m-1])/2;
}
else median=list[m];

System.out.println("Mean is "+mean +" Median is "+median);

}
}

Hope this helps! Do thumbs up! And please ask if you have any doubt.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote