-
Notifications
You must be signed in to change notification settings - Fork 1
/
MeasurableTest_gonz.java
85 lines (71 loc) · 1.63 KB
/
MeasurableTest_gonz.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
public class MeasurableTest_gonz {
public static void main(String[] args) {
int rolls = 10;
DataSet dataSet1 = new DataSet();
DataSet dataSet2 = new DataSet();
for (int i = 1; i <= rolls; ++i) {
Die myDie = new Die();
int n = myDie.roll();
dataSet1.add(myDie);
}
System.out.println("Average: " + dataSet1.getAverage());
dataSet2.add(new Person("Joe", 102));
dataSet2.add(new Person("Bob", 115));
dataSet2.add(new Person("Jack", 2034));
System.out.println("Max Name: " + dataSet2.getMaximum().getName() + " Average height: " + dataSet2.getAverage());
}
}
interface Measurable {
public double getMeasure();
public String getName();
}
class Die implements Measurable{
private final int MAX_FACE = 6;
private int faceValue;
public int roll(){
return faceValue = (int)(Math.random() * MAX_FACE) + 1;
}
public double getMeasure(){
return faceValue;
}
public String getName() {
return null;
}
}
class Person implements Measurable {
private String name;
private int height;
public Person(String name, int height) {
this.name = name;
this.height = height;
}
public String getName() {
return name;
}
public double getMeasure() {
return height;
}
}
class DataSet {
private double sum;
private Measurable maximum;
private int count;
public DataSet() {
sum = 0;
count = 0;
maximum = null;
}
public void add(Measurable x) {
sum = sum + x.getMeasure();
if (count == 0 || maximum.getMeasure() < x.getMeasure())
maximum = x;
count++;
}
public double getAverage() {
if (count == 0) return 0;
else return sum / count;
}
public Measurable getMaximum() {
return maximum;
}
}