Search code examples
stringkotlintextintegercalculator

How to make a string exercise into int in kotlin?


Everything I tried gives an Error, it can handle the numbers but not the "+",what I want is the result to be "10". I'm attempting to make a calculator in android studio... This is what I tried:

var sum = "5+5"
val num = sum.toInt()
exercise.text = "$num" //the text displayed on the screen

Solution

  • I followed a tutorial and I can now answer my own question: You can use implementation 'net.objecthunter:exp4j:0.4.8' in your build gradle, then use .append(string) to add a string into your text and then use

    val expression = ExpressionBuilder(Text.text.toString()).build()
    val result = expression.evaluate()
    val longResult = result.toLong()
    if(result == longResult.toDouble())
       Text.text = "=$longResult"
    else
        Text.text = "=$result"
    

    to evaluate and paste the result in the text you have