A class that remembers
Objects are good at remembering. A class can collect numbers one at a time and answer questions about them whenever it's asked: how many there have been, their total, their average, the largest. This log of bike trips does that:
public class Main {
public static void main(String[] args) {
TripLog log = new TripLog();
log.add(12);
log.add(40);
log.add(5);
System.out.println("Trips: " + log.tripCount());
System.out.println("Total: " + log.totalKm() + " km");
System.out.println("Longest: " + log.longestKm() + " km");
System.out.println("Average: " + log.averageKm() + " km");
}
}public class TripLog {
private int count;
private int total;
private int longest;
public TripLog() {
this.count = 0;
this.total = 0;
this.longest = 0;
}
public void add(int km) {
this.count++;
this.total = this.total + km;
if (km > this.longest) {
this.longest = km;
}
}
public int tripCount() {
return this.count;
}
public int totalKm() {
return this.total;
}
public int longestKm() {
return this.longest;
}
public double averageKm() {
if (this.count == 0) {
return 0.0;
}
return (double) this.total / this.count;
}
}Trips: 3
Total: 57 km
Longest: 40 km
Average: 19.0 km- The log doesn't keep the trips themselves, only what it needs for its answers: how many trips, their sum, and the longest so far. Each
addupdates all three. (Later in the course, an object gets a list of its own.) - The average isn't stored:
averageKm()works it out when it's asked, from the count and the total.(double)turns the total into adoublebefore the division, so the decimals aren't lost (module 4). averageKm()checks for an empty log first. With no trips there's no average, and the method returns 0.0 instead of dividing by zero.
The class does the bookkeeping, and main only gives it numbers and asks questions. The same class works whether the numbers are written in the code, as here, or typed in by a user. What a log like this remembers depends on the questions it has to answer: the challenges below keep track of other things than a count and a total.