Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Daniel Kilders
Daniel Kilders
36,793 Points

How to express operator relevance or how to parse a string expression into an int

Hi! I have not been able to figure this out, so lets see if someone can help me :)

Developing in android studio i've noticed that that I can declare:

int number = ((5-8)*5)/2 ;

and log the comment with no problem. It will output the result of the expression. However, if I want to calculate the same based on user input from 1 edittext, I will get into issues.

How can I parse a string into an int without getting a NumberFormatException and it maintains operator relevance ?

2 Answers

Daniel Kilders
Daniel Kilders
36,793 Points

Hi Ben !

if I use :

Integer.parseInt(myEditText.getText().toString());

EditText content is based on user input. But something as simple as 5+6 will throw a NumberFormatException. Am I right?

EDIT: I'm parsing the whole expression from the same EditText and at the same time!

Ben Deitch
Ben Deitch
Treehouse Teacher

Oh now I see what you mean by 'operator relevance'. Yep, that's correct; the String "5+6" cannot be converted to a number. What you're really looking for then is a way to run Java code that's represented as a String and then retrieve the result of that code. This is a fairly difficult thing to do and I wouldn't recommend it, but I think it can be done by using something like Runtime.exec().

Daniel Kilders
Daniel Kilders
36,793 Points

Hmm... What I'm trying to build is a calculator that allows users to input expressions like " (1+5*(4-2)) " and that shows the result when clicked on the equal button.

What would you recommend me to look into in order to code it in the a proper way ?

Thanks for your help till now :)

Ben Deitch
Ben Deitch
Treehouse Teacher

I'm not entirely sure what the best way would be, but I was able to find a worked calculator example that looks useful.