Question

Hey guys I´m completely new to Scala and need some Help.My goal is to write a programm wich takes a List and a Command as Input.Then it should either return the list, the average Length of the list or the"longest" Entry. Furthermore it shuld ask over and over again for input, and this is what I dont know how to write. Also I have some problems with the formatting ("%.1f"). Does somebody know how to solve these Problems. Thank you very much. This is my code:

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()
}
Was it helpful?

Solution

You need to put

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

part into exercise() function and call it recursively. This is for asking until You type exit

The second problem is getAverageLeng signature it should return Double not Number, and change sum.asInstanceOf[Int] to sum.asInstanceOf[Double] in this function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top