如何在Scala模式匹配中引发异常?

时间:2019-01-06 14:04:46

标签: scala exception pattern-matching match

我有一个字符串“ -3 + 4-1-1 +1 + 12-5 + 6”,我想找到该方程的解。并保护其免受有害字符(例如abc或#)的侵害。

这个方程的解决方案是正确的,但是当字符串中出现其他符号时,我无法处理异常。我正在使用Scala和模式匹配,这对我来说是一个新主题,我不确定为什么它不起作用。

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);

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

应该抛出错误的运算符Exception,但是我有:

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

3 个答案:

答案 0 :(得分:3)

您只需要在尝试转换时将温度分配给0-将其转换为数字,这将为您提供NumberFormatException。

您只需要在每个运算符("-", "+")之后留一个空格就牢记这一点。

object Solution extends App {
  val numberString = "- 3 + 4 - 1 + 1 + 12 - 5  + 6"

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

  var temp = 0


  for (i <- abc.indices) {
    abc(i) match {
      case "+" => temp += abc(i + 1).toInt
      case "-" => temp -= abc(i + 1).toInt
      case x if x.forall(_.isDigit) => println("im a number ")

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

  print(temp)
}

答案 1 :(得分:1)

不要使用可变状态,这是邪恶的...

   val num = """(\d+)""".r // Regex to parse numbers
   @tailrec
   def compute(in: List[String], result: Int = 0): Int = in match {
      case Nil => result
      case "+" :: num(x) :: tail => compute(tail, result + num.toInt)
      case "-" :: num(x) :: tail => compute(tail, result - num.toInt)
      case ("+"|"-") :: x :: _ => throw new Exception(s"Bad number $x")
      case x :: Nil => throw new Exception(s"Invalid syntax: operator expected, but $x found.")
      case op :: _  => throw new Exception(s"Invalid operator $op")

  }

答案 2 :(得分:1)

更正Dima的答案:

val num = """(\d+)""".r // Regex to parse numbers
def compute(in: List[String], result: Int = 0): Int = in match {
  case Nil => result
  case "+" :: num(x) :: tail => compute(tail, result + x.toInt)
  case "-" :: num(x) :: tail => compute(tail, result - x.toInt)
  case ("+" | "-") :: x :: _ => throw new Exception(s"Bad number $x")
  case x :: Nil => throw new Exception(s"Invalid syntax: operator expected, but $x found.")
  case op :: _  => throw new Exception(s"Invalid operator $op")
}