Reputation: 53
I am making a program that solves a math expression, for example, 2+2. Can I set an integer equal to something like this:
val input = "2+2"
input.toInt()
Upvotes: 1
Views: 3465
Reputation: 21
No you cannot convert directly a String Mathematical Expression to Integer.
But you can try following approach to convert String Mathematical Expression to Integer ->>
var exp: String = "2+3-1*6/4"
var num: String = ""
var symbol: Char = '+'
var result: Int = 0
for(i in exp)
{
if(i in '0'..'9')
num += i
else
{
if(symbol == '+')
result += Integer.parseInt(num)
else if(symbol == '-')
result -= Integer.parseInt(num)
else if(symbol == '*')
result *= Integer.parseInt(num)
else if(symbol == '/')
result /= Integer.parseInt(num)
num=""
symbol = i
}
}
//To calculate the divide by 4 ( result/4 ) in this case
if(symbol == '+')
result += Integer.parseInt(num)
else if(symbol == '-')
result -= Integer.parseInt(num)
else if(symbol == '*')
result *= Integer.parseInt(num)
else if(symbol == '/')
result /= Integer.parseInt(num)
println("result is $result") //Output=> result is 6
}
Upvotes: 2
Reputation: 12177
This can be done with the kotlin script engine. For details see Dynamically evaluating templated Strings in Kotlin
But in a nutshell it's like this:
val engine = ScriptEngineManager().getEngineByExtension("kts")!!
engine.eval("val x = 3")
val res = engine.eval("x + 2")
Assert.assertEquals(5, res)
Upvotes: 1
Reputation: 13471
No, Integer cannot be equal to math expression.
You may use String Templates
Strings may contain template expressions, i.e. pieces of code that are evaluated and whose results are concatenated into the string.
A template expression starts with a dollar sign ($) and consists of either a simple name:
val i = 10
val s = "i = $i" // evaluates to "i = 10"
Upvotes: -2
Reputation: 2308
No you can't.
You can like this:
val a = "2"
val b = "2"
val c = a.toInt() + b.toInt()
Or
val input = "2+2"
val s = input.split("+")
val result = s[0].toInt() + s[1].toInt()
Upvotes: 1
Reputation: 89668
Kotlin doesn't have any built in ways for evaluating arbitrary expressions. The toInt
function can only parse a String
containing a single whole number (it's just a wrapper for Integer.parseInt
).
If you need this functionality, you'll have to parse and evaluate the expression yourself. This problem is no different than having to do it in Java, for which you can find discussion and multiple solutions (including hacks, code samples, and libraries) here.
Upvotes: 7