-3
public double median(){
double input =0;
double answer =sum() * (input) / data.length;
    return answer;
    }

This is my code I have for median but it keeps returning as zero when I run the program. The array of numbers are: {3.0, 15.0, 7.0, 27.0};

Min Park
  • 1
  • 1
  • 1

3 Answers3

2

In the code you've provided it looks like you're trying to find the mean not the median. I've provided some code below that should help with finding the mean. To find the median you'd need to sort the array, which is a little more complicated.

The short answer is to remove the input=0 line. Assuming that data is a public variable and that sum is a function that sums that public variable your code should work.

The implementation should depend on the context, but I would recommend a static function that takes an array of doubles as the single argument.

public class Median{
   public static void main(String[] args){
      double numbers[] ={1.0, 2.0, 3.0};
      System.out.println(median(numbers));
   }
   public static double median(double[]x){
      double sum = 0;
      for(int i=0;i<x.length;i++){
         sum += x[i];
      }
      return sum/x.length;
   }
}
ShawSa
  • 56
  • 4
1

You always multiply by zero (input = 0). So it will always return zero.

Stephen84s
  • 76
  • 4
Tobias Horst
  • 135
  • 1
  • 11
0

Try something like this:

public Double average(Double[] array){
    Double sum = 0.0;
    for(int index=0;index<array.length;index++){
        sum+=array[index];
    }
    return sum/array.length;
}