【问题标题】:Scala - Loop + formatScala - 循环+格式
【发布时间】:2014-05-14 19:40:35
【问题描述】:

大家好,我是 Scala 的新手,需要一些帮助。我的目标是编写一个程序,它将一个列表和一个命令作为输入。然后它应该返回列表、列表的平均长度或“最长”的条目。此外,它应该一遍又一遍地要求输入,这是我不知道如何写的。我也有一些格式问题(“%.1f”)。有人知道如何解决这些问题。非常感谢你。这是我的代码:

import scala.io.Source

var input = readLine("Enter a List")
val cmd = readLine("Entera command")

input=input.replace(" ","")
var input2=input.split(",").toList


def exercise() {

   cmd match {
      case "maxLength" => println(getMaxLength(input2))
      case "list" => getList(input2)
      case "averageLength" => println("%.1f".format(getAverageLeng(input2)))
      case "exit" => sys.exit()
      case _ => println("unknown command")

    }

}

def getMaxLength(list:List[String]): String = {
 list match {
  case Nil => return ""
  case _ => return list.fold("")((l, v) => if (l.length > v.length) l else v)
}
}

def getAverageLeng(list:List[String]): Number = {
 list match {
  case Nil => return 0.0
  case _ => return list.map(_.length()).sum.asInstanceOf[Int] / list.length
  }
}

def getList(list:List[String]):Unit =  {
 list match {
  case Nil => return  
  case _ => list foreach println
 }
}
exercise()
}

【问题讨论】:

  • 您看到了什么错误?它发生在您的代码中的什么地方?
  • 当我尝试获取平均长度时,会发生此错误 => 线程“main”中的异常 java.util.IllegalFormatConversionException: f != java.lang.Integer

标签: list scala loops input format


【解决方案1】:

你需要放

var input = readLine("Enter a List")
val cmd = readLine("Entera command")
input=input.replace(" ","")
var input2=input.split(",").toList

加入exercise() 函数并递归调用它。 这是为了询问,直到您输入 exit

第二个问题是getAverageLeng签名它应该返回Double而不是Number, 并在此函数中将sum.asInstanceOf[Int] 更改为sum.asInstanceOf[Double]

【讨论】:

    猜你喜欢
    • 2016-05-03
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2016-08-23
    • 1970-01-01
    相关资源
    最近更新 更多