University of Toronto - Fall 2000
Department of Computer Science
Week 10 - Array Example
Array Example - Statistics for a list
ManageStats.java
import java.io.*;
// ManageStats: This class manages a list of integers. It calculates
// various types of statistics for this list.
public class ManageStats {
public static void main (String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader
(System.in));
// Read the size of the list, 'N'.
System.out.print ("Number of values? ");
int N = Integer.parseInt(in.readLine());
// Declare and instantiate an array 'list' to hold 'N' integers.
int[] list = new int[N];
// Read contents of 'list' from input.
for (int i = 0; i < N; i++) {
System.out.print ("Enter a value: ");
list[i] = Integer.parseInt(in.readLine());
}
// Call the method to print out various statistics
System.out.println ("\nList Statistics:");
System.out.println ("median = " + median(list));
System.out.println ("mean = " + mean(list));
System.out.println ("min = " + min(list));
System.out.println ("max = " + max(list));
System.out.println ("mode = " + mode(list));
}
// median: return the value of the element that is
// the median in 'list'. Note: This does not work if
// the list contains duplicates.
public static int median (int[] list) {
for (int i = 0; i < list.length; i++) {
if (countSmaller(list[i],list) == list.length/2) {
return list[i];
}
}
return -999; // list size of 0.
}
// countSmaller: return the number of entries in 'list'
// that are smaller than 'refVal'.
private static int countSmaller(int refVal, int[] list){
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] < refVal) {
count++;
}
}
return count;
}
// mean: return the average of the elements in 'list'.
public static double mean (int[] list) {
for (int i = 0; i < list.length; i++) {
}
return
}
// min: return the smallest value in 'list'.
private static int min (int[] list){
for (int i = 1; i < list.length; i++) {
}
return
}
// max: return the largest value in 'list'.
private static int max (int[] list){
for (int i = 1; i < list.length; i++) {
}
return
}
// mode: return the most frequently occurring value
// in 'list'. If there is more than one value that
// is the mode, just return the first mode in 'list'.
private static int mode (int[] list){
// Determine count of most frequent element.
int highCount =
for (int i = 1; i < list.length; i++) {
}
return
}
// countSame: return the number of entries in 'list'
// that are same as 'refVal'.
private static int countSame(int refVal, int[] list){
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == refVal) {
count++;
}
}
return count;
}
}
Output for ManageStats.java
Number of values? 9
Enter a value: 6
Enter a value: 8
Enter a value: 6
Enter a value: 5
Enter a value: 4
Enter a value: 6
Enter a value: 3
Enter a value: 8
Enter a value: 3
List Statistics:
median = 6
mean = 5.444444444444445
min = 3
max = 8
mode = 6