In: Computer Science
Question: In a package named "oop" create a Scala class named "Team" and a Scala object named "Referee". Team will have:
• State values of type Int representing the strength of the team's offense and defense with a constructor to set these values. The parameters for the constructor should be offense then defense
• A third state variable named "score" of type Int that is not in the constructor, is declared as a var, and is initialized to 0 Referee will have:
• A method named "playGame" that takes two Team objects as parameters and return type Unit. This method will alter the state of each input Team by setting their scores equal to their offense minus the other Team's defense. If a Team's offense is less than the other Team's defense their score should be 0 (no negative scores)
• A method named "declareWinner" that takes two Teams as parameters and returns the Team with the higher score. If both Teams have the same score, return a new Team object with offense and defense both set to 0
Input:
Team.scala:
package oop
class Team(val offense:Int, val defense:Int){ //Data class with parameterized constructor
var score: Int = 0 //local variable
}
object Referee{
def playGame(team_1:Team, team_2: Team):Unit = { //Method: playGame with return type Unit
/*
Single line if else statement to assign score
If offense is less than other team's defense, assign 0
Otherwise perform offense - defense
*/
team_1.score = if(team_1.offense < team_2.defense) 0 else team_1.offense - team_2.defense
team_2.score = if(team_2.offense < team_1.defense) 0 else team_2.offense - team_1.defense
}
def declareWinner(team_1:Team, team_2: Team):Team = { //Method: declareWinner return type Team
if (team_1.score == team_2.score) //Check if both teams have same score
return new Team(0, 0) //Return object with offense and defense as 0
if (team_1.score > team_2.score) { //Check if first team won
println("Team 1 won!")
return team_1 //return object of first team
}
println("Team 2 won!")
return team_2 //Otherwise return object of second team
}
def main(args: Array[String]): Unit = { //main method
val team_1 = new Team(5,2) //create object for 1st team
val team_2 = new Team(3,7) //create object for 2nd team
playGame(team_1, team_2) //call playGame
val winner = declareWinner(team_1, team_2) //Return object of winning team
}
}
Output:

Explanation: