In java, there is a method eval (String) that evaluates a string as the name of a method, a calculation or something else.
For example:
Code:
alert (eval ("3 +4")); displays the alert box containing 7
But java is not as easy to evaluate a calculation entered by the user for example, must be created or even a method that parses the string and that the calculation result. Here are some tips to help you make a method like this. There are several ways to do this but here is one (I do not know if this is the best):
Code:
Create a method (called eval example):
public double eval (String s) (
/ / Content here
)
Then, a first part of this method takes the contents of the bracket and replace it with his monogram. To isolate the parentheses you can use a split or a substring with indexOf. Let's say you insulate your way of parenthesis that txtAvt contains what is before the parenthesis, txtApres there after and parenthesis the content of the parenthesis.
You can then do:
Code:
return eval (sometxt + eval (parenthesis). toString () + txtApres)
After that (if there is no parenthesis method continues to run until you get on another return) must be cut string (with a split) that the sums and differences: Indeed, if we calculate 3 / 2 5 * 3 must first be 3 / 2 | (5 * 3)
If you have a String [] sum which contains eg all are doing a loop that adds eval (sum [i]) to a variable (result, for example) and variable return (result) at the end of the loop:
Code:
double result = 0;
for (int i = 0; i <temp.length i + +) (
result + = sum [i];
)
return result;
Same process for multiplication and division. And the end of your method will be executed only if no more + - * / and () in your string then you can make a Double.parseDouble (s) if s is the string to convert. Remember to make a try (... ) Catch (NumberFormatException e) ... ( ) In order to prevent errors.
Supplementary Note :
Beware, the split with the views (*) and more + not working properly because the split takes into account the regular expressions. A simple solution is to
Code:
s.replace ('+',' P '). split ("P");
instead of
(But do not contain other characters s 'P'!) and
Code:
s.replace ('*',' x '). split ("x");
instead of
You can also make a s.replace (',','.'); that commas are correctly interpreted by Double.parseDouble (s)! (3.2345 dismissal if an error because you must write 3.2345)
If you still have queries then you can follow this
Eval function in javascript
Bookmarks