【发布时间】:2016-11-11 23:24:24
【问题描述】:
我的系统允许用户搜索“库存”数据列表以显示每个数据。目前他们可以搜索股票列表中的最小值和最大整数。我正在努力做到这一点,以便他们可以找到“当前”股票价格,因此是列表尾部的最后一个元素。 我以前有这个,但是这不符合我的映射列表;
// last element
def lastif(ls:List[Int]):Int = {
if(ls.tail == Nil)
ls.head
else
lastif(ls.tail)
}
这就是我所拥有的,包括底部不起作用的东西
def allStockLevel(team: String): (String, List[Int]) =
(team, mapdata.get(team).getOrElse(List.empty))
//Shows Highest Stock
def highestStockLevel(stock: String): (String, Int) =
(stock, mapdata.get(stock).map(_.max).getOrElse(0))
//Shows the Lowest Stock
def lowestStockLevel(stock: String): (String, Int) =
(stock, mapdata.get(stock).map(_.min).getOrElse(0))
//Show last element in the list, most current
def currentStockLevel (team: String): (String, Int) = {
if (team.tail == Nil)
team.head
else
currentStockLevel(ls.tail)
}
相关处理程序
// handlers for menu options
def handleOne(): Boolean = {
mnuShowPoints(currentPoints)
true
}
相关功能
def mnuShowSingleDataStock(f: (String) => (String,Int)) = {
print("Stock>")
val data = f(readLine)
println(s"${data._1}: ${data._2}")
}
列表正在从txt文件中读取
// read data from file
val mapdata = readFile("data.txt")
// UTILITY FUNCTIONS
//GETS THE DATA FROM THE DATA.TXT
def readFile(filename: String): Map[String, List[Int]] = {
processInput(Source.fromFile(filename).getLines)
}
def processInput(lines: Iterator[String]): Map[String, List[Int]] = {
Try {
lines.foldLeft(Map[String, List[Int]]()) { (acc, line) =>
val splitline = line.split(",").map(_.trim).toList
acc.updated(splitline.head, splitline.tail.map(_.toInt))
}
}.getOrElse {
println("Sorry, an exception happened.")
Map()
}
}
【问题讨论】:
-
你得到什么错误?
-
@marstran 类型不匹配,找到 char,需要字符串 int
-
这是因为
team.head返回一个Char。您的team参数是String。head函数返回第一个元素String,即Char。您不会在任何地方构造(String, Int)。 -
如何更改它,以便第一个元素 Char 作为字符串 int 返回?或者有没有更有效的方法? @marstran
-
您的
currentStockLoevel当前定义为:给我一个String,我会给您返回一对(String, Int)- 因此您的错误。