Spaces:
Running
Running
| Finally, write a class to model one football match. | |
| So write a (non-public) class 'Match' with the following properties: | |
| Attributes team1 and team2, with type Team | |
| Attributes of integer type goals1 and goals2 | |
| A constructor that takes teams 1 and 2 as parameters (but not goal totals). | |
| Method void addGoal(Team team), which increases the number of goals of the given team by one | |
| Method printStatus(), which prints the game status in the format shown in the example below; | |
| Example output when calling the method printStatus: | |
| FCT - UniFC: 1 - 0 | |
| import java.lang.reflect.Field; | |
| import java.util.ArrayList; | |
| import java.util.HashMap; | |
| import java.util.Random; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| System.out.println("Testing class Match..."); | |
| Team t1 = new Team("FCT"); | |
| Team t2 = new Team("UniFC"); | |
| Match match = new Match(t1, t2); | |
| System.out.println("Match object created!"); | |
| for (String fname : new String[] {"team1", "team2", "goals1", "goals2"}) { | |
| try { | |
| Field fld = match.getClass().getDeclaredField(fname); | |
| boolean isPrivate = fld.getModifiers() == 2; | |
| System.out.println(fname + " is private: " + isPrivate); | |
| } catch (Exception e) { | |
| System.out.println("Attribute " + fname + " is not defined"); | |
| } | |
| } | |
| System.out.println("Starting situation: "); | |
| match.printStatus(); | |
| System.out.println("Adding goals..."); | |
| match.addGoal(t1); | |
| match.printStatus(); | |
| match.addGoal(t2); | |
| match.printStatus(); | |
| match.addGoal(t1); | |
| match.printStatus(); | |
| match.addGoal(t1); | |
| match.printStatus(); | |
| match.addGoal(t2); | |
| match.printStatus(); | |
| } | |
| } | |
| //ADD | |
| class Match { | |
| // attributes | |
| private Team team1; | |
| private Team team2; | |
| private int goals1; | |
| private int goals2; | |
| // constructor | |
| public Match(Team team1, Team team2) { | |
| this.team1 = team1; | |
| this.team2 = team2; | |
| // remember to initialise attributes to avoid nullpointerexception | |
| this.goals1 = 0; | |
| this.goals2 = 0; | |
| } | |
| public void addGoal(Team team) { | |
| if (team1.equals(team)) { | |
| this.goals1 += 1; | |
| } | |
| else { | |
| this.goals2 += 1; | |
| } | |
| } | |
| public void printStatus() { | |
| System.out.println(this.team1.getName() + " - " + this.team2.getName() + ": " + this.goals1 + " - " + this.goals2); | |
| } | |
| } | |
| Testing class Match... | |
| Match object created! | |
| team1 is private: true | |
| team2 is private: true | |
| goals1 is private: true | |
| goals2 is private: true | |
| Starting situation: | |
| FCT - UniFC: 0 - 0 | |
| Adding goals... | |
| FCT - UniFC: 1 - 0 | |
| FCT - UniFC: 1 - 1 | |
| FCT - UniFC: 2 - 1 | |
| FCT - UniFC: 3 - 1 | |
| FCT - UniFC: 3 - 2 | |