[英]How to throw exception in Scala pattern matching?
我有一個字符串“ -3 + 4-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: "#"
您只需要在嘗試進行轉換時將臨時分配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)
}
不要使用可變狀態,這是邪惡的...
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")
}
更正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")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.