/* File: Team.java - March 2011 */ package l08; /** * A container class for a team's record: wins, losses, draws and * goal difference. Intended as an illustration of the Comparable interface. * * @author Michael Albert * */ public class Team implements Comparable{ public static final int WIN_POINTS = 3; public static final int DRAW_POINTS = 1; private String name; private int wins = 0; private int draws = 0; private int losses = 0; private int goalDifference = 0; public Team(String name) { this.name = name; } public void addResult(int goalsFor, int goalsAgainst) { if (goalsFor > goalsAgainst) { wins++; } else if (goalsFor < goalsAgainst) { losses++; } else { draws++; } goalDifference += goalsFor - goalsAgainst; } public int getPoints() { return wins*WIN_POINTS + draws*DRAW_POINTS; } public int compareTo(Team other) { // First compare based on total points int pointsDifference = this.getPoints() - other.getPoints(); if (pointsDifference != 0) { return pointsDifference; } // If that doesn't work, try goal difference int gd = this.goalDifference - other.goalDifference; if (gd != 0) { return gd; } // As a last resort compare alphabetically return this.name.compareTo(other.name); } public String getName() { return name; } public String toString() { return name + " " + getPoints() + " points " + "(W: " + wins + ", L: " + losses + ", D: " + draws + ", GD: " + goalDifference +")"; } }