我有一个名为“readStock”的函数,它应返回[String,WeatherReading]类型的值,而“WeatherReading”是案例类“WeatherReadingStub”的对象。我不知道如何为函数“readStock”声明和返回对象。
代码: -
package HW9
object WeatherStub {
//Setting file name
val fileName = "weather.csv"
//Calling Main
def main(args: Array[String]): Unit = {
val weatherData: Map[String, WeatherReading] = readWeather(fileName)
printWeather(weatherData)
}
def readWeather(fn: String): Map[String,WeatherReading] = {
//Creating a mutable map to collect all the values
val weatherMuteMap = scala.collection.mutable.Map[String, WeatherReading]()
//Checking for empty or null values
def IsEmptyOrNull(s: String): Option[Float] = {
if ((s ne null) && s.trim.length > 0) Some(s.toFloat) else None
}
//Reading file
for (line <- io.Source.fromFile(fn).getLines()) {
val list1 = line.split(",", -1).map(_.trim).toList
//Setting up default values
val TotalPrecp: Option[Float] = IsEmptyOrNull(list1(1).toString) match { case Some(i) => Some(i) case _ => None}
val LowPrecp: Option[Float] = IsEmptyOrNull(list1(2).toString) match { case Some(i) => Some(i) case _ => None}
val HighPrecp: Option[Float] = IsEmptyOrNull(list1(3).toString) match { case Some(i) => Some(i) case _ => None}
//Creating object for the case class WeatherReadingStub
val WeatherReading = WeatherReadingStub(TotalPrecp,LowPrecp,HighPrecp)
//Adding elements to the mutable list
weatherMuteMap(list1(0).toString) = WeatherReading.toString
}
//Converting to Immutbale Map
weatherMuteMap.toMap
}
def printWeather(weatherMap: Map[String, String]): Unit = {
//Format of the message to be printed
println("(Date,{Precipitation,LowTemperature,HighTemperature})\tAverageTemperature")
//Printing the average temp values calculated in Case Class using object
weatherMap.toSeq.sortBy(_._1).foreach(wd => println(wd + "\t" + wd._2.averageTemperature.getOrElse("N/A")))
println
}
}
案例类代码: -
package HW9
case class WeatherReadingStub(precipitation: Option[Float], lowTemperature: Option[Float], highTemperature: Option[Float]) {
def averageTemperature: Option[Float] = (lowTemperature, highTemperature) match {case (Some(i),Some(j)) => Some((i + j)/2) case _ => None}
override def toString: String = s"{${precipitation.getOrElse("MISSING")},${lowTemperature.getOrElse("MISSING")},${highTemperature.getOrElse("MISSING")}}"
}
答案 0 :(得分:0)
检查您的班级名称WeatherReadingStub。在Object WeatherStub中, readWeather方法使用键构建一个可变的Map,日期(类型为String),value是WeatherReading对象。您的类WeatherReadingStub具有averageTemperature,并且您在MAP [String,WeatherReadingStub]中引用了WeatherReadingStub。如果将WeatherReading替换为已定义的对象WeatherReadingStub,则此程序将运行。 你对MAP的定义应该是 val weatherData:Map [String,WeatherReadingStub] = readWeather(fileName)(替换所有其他出现次数。)