简体   繁体   English

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

[英]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. 我有一个字符串“ -3 + 4-1 + 1 + 12-5 + 6”,我想找到该方程的解。 And secure it from unwanted characters in it (like abc, or #). 并保护其免受有害字符(例如abc或#)的侵害。

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. 我正在使用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);

Output when 输出时

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

should be throwing wrong operator Exception but I have: 应该抛出错误的运算符Exception但我有:

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

you just need to assign 0 to the temp as you are trying to convert - into digit it's giving you the NumberFormatException. 您只需要在尝试进行转换时将临时分配0即可-转换为数字即可获得NumberFormatException。

you just need to keep that in mind after every operator ("-", "+") there should be a space. 您只需要在每个运算符("-", "+")之后留一个空格就牢记这一点。

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

Don't use mutable state it's evil ... 不要使用可变状态,这是邪恶的...

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

  }

Correcting Dima's answer: 更正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