Question:
Is there a java method that calculates strings?
Anuj Kalra
2013-07-21 09:03:24 UTC
I have a a program here:
class A
{
public static void main(String []p)
{
String str1;
str1="10+2*6";
Integer i1;
/* Here comes the code that calculates string and returns a result in integer format */
System.out.println(i1);
//for(int i=0;i }
}

Is there a way to do this or is it just wishful thinking?
Four answers:
anonymous
2013-07-21 09:51:13 UTC
I don't believe so. Just make the function yourself, separate it into substring based on the index of the arithmetic operators then, place all the substrings (arithmetic operators as a char) into an array, then go through that array and cast the string numbers into integers and based on what operator was between then apply that to the integer numbers, and store those calculations in a variable that will be returned. So the array should look like:



["10","+","2","*","6"]



Assuming the user order is correct. You would check if the string is a number to cast it into an integer, then go through and calculate making sure do it in the order of Order of Operations. In this case it would find "+" and "*", from the indexOf("*")=timesIndex do { array[timesIndex-1]*array[timesIndex+1] }. And While there are still are arithmetic operators, repeat that recursively. So for that the process should look like:



["10","+","2","*","6"]



[10,"+",2,"*",6] ( "+", "*" )



[10,"+",12] ("+")



[22] (No operators found, problem is done.)



You also have to account for items in between "(" and ")" are exceptions, find those first and do the operations on those as substrings then the main problem after. If you use recursion right this can turn into a beautifully short amount of code.
?
2013-07-21 16:42:08 UTC
http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form



Apparently you can use the built in javascript engine with JDK 1.6 to automatically do this for you, although the overhead seems a little overboard for doing such a thing.



But for the most part, if you want to be able to prevent and capture syntax errors which the engine may not do for you, you would have to parse and evaluate the string yourself.
anonymous
2013-07-21 17:19:55 UTC
Beanshell appears to be what you're after: http://www.beanshell.org/



The 'eval' method in the Interpreter class should do the trick:

http://www.beanshell.org/javadoc/index.html
dude
2013-07-21 17:42:56 UTC
You want BigInteger



http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...