I am a beginner trying to learn Scala.
This is a small program I tried to write to calculate expressions in the correct order -
object Calc extends App {
while (true) {
val input: String = scala.io.StdIn.readLine("> ")
println(evaluate(input))
}
def evaluate(input: String) = {
val finput = input.replace(" ", "")
var elems = new Array[String](finput.length())
var last = elems.length
for (i <- 0 to last - 1) {
elems(i) = finput.substring(i, i + 1)
}
val operators: Array[String] = Array("/", "*", "+", "-")
for (i <- 0 to operators.length) {
while (elems contains operators(i)) {
val pos = elems.indexOf(operators(i))
val a = elems(pos-1).toInt
val b = elems(pos+1).toInt
var found = 0
elems(pos) match {
case "/" => found = a/b
case "*" => found = a*b
case "+" => found = a+b
case "-" => found = a-b
}
elems(pos-1) = found.toString()
last = last - 2
for (j <- pos to last) {
elems(j) = elems(j + 2)
}
}
}
elems(0)
}
}
This program does not work, I get a runtime error at elems(j) = elems(j + 2). Could someone tell me why?
Also, is the program design okay?