1

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: "#"
1
  • 1
    the problem is you are trying to convert # into int which is causing the exception what you can do is check for isDigit and in the else party raise an Exception you want Commented Jan 6, 2019 at 14:09

3 Answers 3

4

you just need to assign 0 to the temp as you are trying to convert - into digit it's giving you the 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)
}
Sign up to request clarification or add additional context in comments.

Comments

1

Correcting Dima's answer:

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

Comments

0

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

  }

3 Comments

OP mentioned they're new to pattern matching. I like your solution, but it might be useful to add an explanation of how you used cons in your match cases.
@codenoodle feel free to edit and add an explanation where you feel it is necessary.
The OP specifically said "it's a new topic" for them, and not only is this vague and unclear to me (and it's not a new topic to me), it isn't even working code. Sorry, but this is just a bad answer and isn't worth editing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.