我在Scala代码中找不到问题。下面的任务。
Input: val team1: Team = new Team(8,6)
val team2: Team = new Team(6,4)
Output for 'play' method: team1.score = 4
team2.score = 0
Output for 'Winner' method: team1
任务:
创建一个名为“ Team”的Scala类和一个名为“ Referee”的Scala对象。
团队将拥有:
•类型为Int的状态值代表团队的进攻和防守实力,并由构造函数设置这些值。构造函数的参数应先冒犯然后防御
•名为Int类型的第三个状态变量“分数”
裁判将具有:
•名为“ play”的方法,该方法将两个Team对象作为参数,并且不返回值。此方法将通过设置每个得分等于其进攻得分减去另一个防守得分的得分来改变每个输入团队的状态。如果一个球队的进攻少于另一个球队的防守,他们的得分应为0(无负得分)
•名为“ Winner”的方法,该方法将两个Teams作为参数并返回得分较高的Team。如果两个队伍得分相同,则返回进攻和防守均设为0的新Team对象。
class Team(var offense: Int, var defense: Int){
var score: Int = 0 //<-Updated Variable
}
object Referee{
def play(team1: Team, team2: Team) = {
team1.score = team1.offense - team2.defense
team2.score = team2.offense - team1.defense
if (team1.offense < team2.defense){
team1.score = 0
}
else if(team2.offense < team1.defense){
team2.score = 0
}
}
def Winner(team1: Team, team2: Team) = {
if (team1.score > team2.score){
team1
}
else if(team2.score > team1.score){
team2
}
else{
new Team(0, 0)
}
}
}
答案 0 :(得分:3)
赋值没有返回值。因此,您要创建一个新的Team
,并将其分配给变量p
,然后将其丢弃。
删除val p =
部分。
答案 1 :(得分:2)
您设置的“任务”本质上是无法运行的,因此与Scala配合得不好。只是为了好玩,这是解决该问题的一种更实用的方法,可以避免任何可变的值:
case class Team(offense: Int, defense: Int) {
def score(other: Team): Int = Math.max(0, offense - other.defense)
}
case class TeamScore(team: Team, score: Int) {
def beats(other: TeamScore): Boolean = score > other.score
}
case class Result(score1: TeamScore, score2: TeamScore) {
def winner: Option[Team] =
if (score1 beats score2) {
Some(score1.team)
} else if (score2 beats score1) {
Some(score2.team)
} else {
None
}
}
object Referee {
def play(team1: Team, team2: Team): Result =
Result(
TeamScore(team1, team1.score(team2)),
TeamScore(team2, team2.score(team1))
)
}