0

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 
4
  • where does "5+5" come from? Commented Aug 9, 2021 at 16:46
  • 2
    I mean technically you're hoping there's already a calculator built into the toInt call, which there isn't! If you want to parse a string as a set of numbers and operations, that's kinda complicated, but doable if you keep it simple (you'd be better finding a tutorial on it though if you're a beginner). If you want to actually make a typical calculator app, you'd be storing button presses instead, not holding the whole thing as a string and trying to work out what it means at the end Commented Aug 9, 2021 at 16:51
  • cactustictacs, you're right! thank you for fixing my thinking process! I might try that, but I'm attempting to start coding with no tutorials because I often get into a tutorial loop or "hell" if you will and can't find my own way of doing things. Commented Aug 9, 2021 at 19:26
  • Mathematical expressions would need to be parsed.  If you want to learn how to write a parser, they're probably a very good place to start, as the language is fairly simple and well-understood!  Otherwise, you'd need to find a library you can use. Commented Aug 9, 2021 at 20:22

2 Answers 2

1

Use eval function insted of toInt() , just a little research See

*Above is only available for Kotlin/Js.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I'll be sure to try that!
Note the big scary warning in the linked docs about how that “is an enormous security risk”.  A hand-written or library parser would be far safer — and probably a lot faster too.
but op wants to build a calculator!
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.