I am iterating an int array to find the median, and then return the median, this portion of the program seems to work.
However, the median has to be cast to a double and it's showing the decimal place but it's not producing the correct output, why?
import java.util.*;
public class Example
{
public static void main(String[] args)
{
int[] exampleArray = {2, 5, 10, 19, 23, 34};
System.out.println("Median is: " + findMedian(exampleArray));
// The output produced here should be 14.5 not 14.0
}
public static double findMedian(final int[] tempArray)
{
int median = 0,
Index = tempArray.length / 2;
if(tempArray.length % 2 == 1)
{
median = tempArray[Index];
/* I believe the problem is breaking down here I can't cast Index or
the tempArray to a double. I can copy the array elements into a new double array
but I tried that as well and the output was still off.
*/
}
else
median = (tempArray[Index] + tempArray[Index - 1]) / 2;
return (double)median;
}
}