Spaces:
Running
Running
File size: 2,950 Bytes
d90f885 | 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | 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
|