dimanche 6 janvier 2019

How to throw exception in Scala pattern matching?

I have a string "-3 + 4 - 1 + 1 + 12 - 5 + 6" and I want to find solution to this equation. And secure it from unwanted characters in it (like abc, or #).

Solution of this equation is correct but I can't handle exception when other signs in string occure. I'm using Scala and pattern matching, it's a new topic for me and I'm not sure why it doesnt work.

object Main extends App {

  val numberString = "-3 + 4 - 1 + 1 + 12 - 5  + 6";

  val abc:  List[String] = numberString.split("\\s+").toList

  var temp = abc.head.toInt


  for (i <- 0 until abc.length) {
    abc(i) match {
      case "+" => temp += abc(i+1).toInt
      case "-" => temp -= abc(i+1).toInt
      case x if -100 to 100 contains x.toInt=> println("im a number ")

      case _ => throw new Exception("wrong opperator")

     }

}

println(temp);

Output when

numberString = "-3 + 4 # - 1 + 1 + 12 - abc 5 + 6";

should be throwing wrong operator Exception but I have:

Exception in thread "main" im a number 
im a number 
java.lang.NumberFormatException: For input string: "#"

Aucun commentaire:

Enregistrer un commentaire