|
Missing Values
A Programming Pattern |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
double values and
a sentinel like -1 for missing valuesnull can be used as a sentinel for all
reference typesDouble
or Integer)valueOf() method to construct the
wrapper object, otherwise leave it null
null
doubleValue() or intValue()
method to retrieve the value
total = 0.0;
for (int i = 0; i < data.length; i++) {
if (data[i] == null) {
total += defaultValue; // Initialized elsewhere
} else {
total += data[i].doubleValue();
}
}
average = total / (double) data.length;
missing = false;
total = 0.0;
for (int i = 0; i < data.length; i++) {
if (data[i] == null) {
missing = true;
break; // No reason to continue iterating
} else {
total += data[i].doubleValue();
}
}
if (missing) {
result = null;
} else {
result = Double.valueOf(total / (double) data.length);
}