【发布时间】:2017-05-20 10:40:21
【问题描述】:
我有允许用户比较地图中包含的两个团队的功能。地图中包含的数据是从一个文本文件中读取的,该文本文件包含有关足球队及其过去 5 个赛季的积分记录的信息。数据存储为 Map[String, List[Int]]:
Manchester United, 72, 86, 83, 90, 94
Manchester City, 80, 84, 91, 77, 88
Chelsea, 76, 85, 92, 87, 84
Arsenal, 70, 79, 81, 76, 83
Liverpool, 69, 77, 80, 73, 79
以下功能允许用户输入两支球队的名称,并比较两支球队最近(最后)得分之间的差异。
val teamdata = readTextFile("teams.txt")
//User presses 2 on keyboard, this invokes menuCompareTeams which invokes compareTeams
def menuOptionTwo(): Boolean = {
//2 - compare 2 teams selected by the user
menuCompareTeams(compareTeams)
true
}
//Function which displays the results of compareTeams
def menuCompareTeams(f: (String, String) => ((String, Int), (String, Int), String)) = {
val input = f(readLine("Enter first team to compare>"),
readLine("Enter second team to compare>"))
println(s"""|Team 1: ${input._1._1} - Points: ${input._1._2}
|Team 2: ${input._2._1} - Points: ${input._2._2}
|${input._3}""".stripMargin)
}
///Function which compares the 2 teams - invoked by menuCompareTeams
def compareTeams(team1: String, team2: String): ((String, Int), (String, Int), String) = {
def lastPoints(list: List[Int]): Int = list match {
case Nil => throw new Exception("Empty list")
case h :: Nil => h
case _ :: tail => lastPoints(tail)
}
val team1Points = teamdata.get(team1) match{
case Some(p) => lastPoints(p)
case None => 0
}
val team2Points = teamdata.get(team2) match{
case Some(p) => lastPoints(p)
case None => 0
}
val pointsComparison = if(team1Points > team2Points){
"The team who finished higher is: " + team1 + ", their total points tally for last season was: " + team1Points + ". There was a difference of " + (team1Points-team2Points) + " points between the two teams."
}
else if(team1Points == team2Points){
"The teams had equal points last season: " + (team1Points|team2Points)
}
else{
"The team who finished higher is: " + team2 + ", their total points tally for last season was: " + team2Points + ". There was a difference of " + (team2Points-team1Points) + " points between the two teams."
}
((team1, team1Points), (team2, team2Points), pointsComparison)
}
例如用户输入“Manchester United”和“Manchester City”时的正确输出如下所示:
第 1 队:曼联 - 积分:94
第 2 队:曼城 - 积分:88
排名靠前的球队是:曼联,他们上赛季的总积分是:94,两队相差6分。
有没有更好或更实用的方法来做我目前正在做的比较 2 个团队的事情?
编辑:我已根据 Alex 的建议编辑了问题。
【问题讨论】:
-
带有多个问题的超长文本。我想建议你把它分成多个问题。从基础开始:如何更好地根据赛季成绩比较两支球队。
-
@AlexFruzenshtein 感谢您的反馈,我已根据您的建议编辑了问题。
标签: scala functional-programming maps comparison