Hello,
I am a beginner programmer in Java. I got stuck with one of the exercises and do not understand what could be wrong.
I cannot find out what is the issue with my median calculation....
My program should roll one dice (1-6) number of times. The program shall then collect how many of each dice value was computed.
The program should also calculate average value and median value. The output should look like:
Number of rolls :
xxx times of dice value 1
xxx times of dice value 2
xxx times of dice value 3
xxx times of dice value 4
xxx times of dice value 5
xxx times of dice value 6
Average:
Median:
Here is my code:
import java.util.Arrays; import java.util.Scanner; public class DiceGame { public static void main (String[] args) { Scanner inputReader = new Scanner(System.in); //Array or each dice value int[] number = new int[]{1, 2, 3, 4, 5, 6}; //Array for collecting number of each dice value int[] counter = new int[6]; //number of executions: int exec = 11; //Array to calculate median int[] medianArray = new int[exec]; // Variables needed to calculate median and average values double sum = 0; double average = 0; double median = 0; //Prints how many executions System.out.println("Number of rolls" + exec); for(int i =0 ; i < exec ; i++) { //Roll the dice int dice=(int)(Math.random()*6); //For each roll count each value counter[dice]++; //For each roll store result in Array medianArray[i] = dice; } for(int j = 0 ; j < 6 ; j++) { System.out.println(counter[j]+" times of dice value "+number[j]); sum = sum + (counter[j] * number[j]); } average = sum / exec; System.out.println("Average " + average); // Sort medianArray: Arrays.sort (medianArray); //If number of elements are an even number: if (medianArray.length % 2 == 0) { median = (medianArray[medianArray.length/2] + medianArray[(medianArray.length/2) +1]) /2; System.out.println("Median "+ median); } //Otherwise the median value is in the middle: else { median = medianArray[((medianArray.length)/2)]; System.out.println("Median "+ median); } } }
Output looks like:
Number of rolls11
3 times of dice value 1
0 times of dice value 2
2 times of dice value 3
2 times of dice value 4
2 times of dice value 5
2 times of dice value 6
Average 3.5454545454545454
Median 3.0
The meedian value is not correct, it should be the 6th value in the sorted medianArray, in other words value 4.
What could be wrong in my code?