public class Scoreboard {
private String team1Name;
private String team2Name;
private int team1Score;
private int team2Score;
private boolean isTeam1Active;
// The parameters here (t1, t2) must match the names used below
public Scoreboard(String t1, String t2) {
team1Name = t1;
team2Name = t2;
team1Score = 0;
team2Score = 0;
isTeam1Active = true;
}
public void recordPlay(int points) {
if (points > 0) {
if (isTeam1Active) {
team1Score += points;
} else {
team2Score += points;
}
} else {
// Points is 0, so switch the active team
isTeam1Active = !isTeam1Active;
}
}
public String getScore() {
String activeName;
if (isTeam1Active) {
activeName = team1Name;
} else {
activeName = team2Name;
}
// Final check: Note the "+" before activeName
return team1Score + "-" + team2Score + "-" + activeName;
}
}
Output(from code runner on pages, I can’t screenshot on this device)
(Step 2) info = 0-0-Red
(Step 4) info = 1-0-Red
(Step 6) info = 1-0-Blue
(Step 7) info = 1-0-Blue
(Step 9) info = 1-3-Blue
(Step 12) info = 1-4-Red
(Step 16) info = 1-8-Red
(Step 18) match info = 0-0-Lions
(Step 19) game info = 1-8-Red
Challenges
My biggest challenge working on this homework assignment was syntax. I often forgot to add semicolons, and I also struggled with the syntax of the return statement, forgetting a plus.
Things I learned
State Management: Using a boolean like isTeam1Active is a very efficient way to handle a “toggle” system. It makes the recordPlay logic clean because ythere are only two states to worry about.
Logic in recordPlay: use of the exclamation point (!isTeam1Active) to flip the boolean is the idiomatic way to handle switches in Java. concise and prevents from having to write if (isTeam1Active) { isTeam1Active = false; }.
String Formatting: In getScore(), String Concatenation is used. By combining integers (team1Score) with string literals (“-“), Java automatically converts numbers into strings to build the final output.