繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM