Hello,

Is there a way to take a String, for instance "4 * 5" from a JTextField and convert it into an expression where I will get a result? Thank you.

Recommended Answers

All 8 Replies

Yes, but you need to manipulate the string yourself. You will need to use a StringTokenizer to break the String up, and the Integer.parseInt method to work out the numbers (assuming floats and doubles are invalid). Have a go and see what you come up with, post back with your code if you need more help.

I suggest avoid using StringTokenizer class its a legacy class, to quote the javadocs of version 1.4.2:-

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

I would suggest using regular expressions similar. Of course in the end you will definitely have to use Integer.parseInt() (or Float.parseFloat() or ..) to convert the numbers from the string to their appropriate types.
This is the best resource for learning how to use regular expressions in Java.

Oh yes, I forgot that StringTokenizer had been discouraged from use. I didn't realise that Java had a String.split method too, so thanks for the tip stephen84 :)

Thank you both for the tips. I will try them out.

You might want to use the trim method as well.
If the user enters: " 4 * 3 "
Then the trim method will return this: "4 * 3"

String expr = "  4    *    3   ";
expr = expr.trim();

BURN THE HERETIC.
KILL THE MUTANT.
PURGE THE UNCLEAN.

FOR THE EMPEROR!!!!

Rape the horses and Pillage the women!
<Pause>
Ah, I mean .....

commented: Dawn of War II is coming Feb 28 +5

Rape the horses and Pillage the women!
<Pause>
Ah, I mean .....

O.o

... wow ....

may i suggest that you look at the first thread i started after my joining Daniweb? it has a solution to the problem that i got from a book (the art of java, search it on amazon), but i do suggest that you don't look at it until you try something yourself... so, i'll leave it up to you to find, i do have some advice

Think recursively (especially if you want the user to be able to use parenthesis),
use simple cases to work out how it should operate,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.