I'm trying to calculate the total, mean and median of an array thats populated by input received by a textfield. I've managed to work out the total and the mean, I just can't get the median to work. I think the array needs to be sorted before I can do this, but I'm not sure how to do this. Is this the problem, or is there another one that I didn't find? Here is my code:
import java.applet.Applet; import java.awt.Graphics; import java.awt.*; import java.awt.event.*; public class whileloopq extends Applet implements ActionListener { Label label; TextField input; int num; int index; int[] numArray = new int[20]; int sum; int total; double avg; int median; public void init () { label = new Label("Enter numbers"); input = new TextField(5); add(label); add(input); input.addActionListener(this); index = 0; } public void actionPerformed (ActionEvent ev) { int num = Integer.parseInt(input.getText()); numArray[index] = num; index++; if (index == 20) input.setEnabled(false); input.setText(""); sum = 0; for (int i = 0; i < numArray.length; i++) { sum += numArray[i]; } total = sum; avg = total / index; median = numArray[numArray.length/2]; repaint(); } public void paint (Graphics graf) { graf.drawString("Total = " + Integer.toString(total), 25, 85); graf.drawString("Average = " + Double.toString(avg), 25, 100); graf.drawString("Median = " + Integer.toString(median), 25, 115); } }
To find median: First, simply sort the array. Then, check if the number of elements present in the array is even or odd. If odd, then simply return the mid value of the array. Else, the median is the average of the two middle values.
Refer an algorithm given below to calculate the median. Step 1 − Read the items into an array while keeping a count of the items. Step 2 − Sort the items in increasing order. Step 3 − Compute median.
Median formula when a data set is even Determine if the number of values, n, is even. Locate the two numbers in the middle of the data set. Find the average of the two middle numbers by adding them together and dividing the sum by two. The result of this average is the median.
The Arrays class in Java has a static sort function, which you can invoke with Arrays.sort(numArray)
.
Arrays.sort(numArray); double median; if (numArray.length % 2 == 0) median = ((double)numArray[numArray.length/2] + (double)numArray[numArray.length/2 - 1])/2; else median = (double) numArray[numArray.length/2];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With