jGuru Forums

How to calculate (3*(4+sin30)*4) in java
1 posts in topic
Flat View
TOPIC ACTIONS:

Posted By:   SAIRAM_CHENNUBHOTLA
Posted On:   Tuesday, March 18, 2003 11:28 PM

Sir I have searched for the right bracket using push and pop opeartions but I have stored all in a string for example 4+sin30 as a string but how to convert from string to calculate that value. Please send the java code if possible.

Thank you
SAIRAM
sairam_cv1@rediff.com
sairam_cv@yahoo.co.in

Re: How to calculate (3*(4+sin30)*4) in java

Posted By:   David_Bates
Posted On:   Wednesday, March 19, 2003 06:37 AM

OK. First of all a disclaimer. This is by no means the way it write a parser. It should be much more modular and flexiable. Here's some code I knocked up:
`import java.util.StringTokenizer;public class ParserTest {	public static void main(String[] args) {		String input = "4+sin30";		double result = evaluate(input);		System.out.println(result);	}	public static double evaluate(String input) {		double result = 0.0;		StringTokenizer st = new StringTokenizer(input, "+-*/", true);		// Is it a single value?			if(st.countTokens() == 1) {			String token = st.nextToken();			if (token.startsWith("sin")) {				// Get the remaining number				token = token.substring(3);									return Math.sin(toRadians(token));			}			else {				return Double.parseDouble(token);			}		}		// Must be an expression.  We'll assume that it's a binary operation		String op1 = st.nextToken();		char op  = st.nextToken().charAt(0);		String op2 = st.nextToken();		switch (op) {			case '+':				// Evaluate each expression either side of the '+'				result = evaluate(op1) + evaluate(op2);				break;		}		return result;	}	// The string passed in is in degrees.	// Convert it to a number in radians	public static double toRadians(String strDegrees) {		double result = Double.parseDouble(strDegrees);		result *= Math.PI;		result /= 180;		return result;	}}`

OK. A few points to note:

• In order to do what you want, you must parse the String to determine the correct operations and then execute those operations. You can't just 'run' a String - unlike in JavaScript where you can just call 'eval()'.

• Your string "4+sin30" is in degrees. This value ('30') must be converted into radians to be used by Math.sin(). That is what my 'toRadians()' method does.

• You should recursively evaluate each expression into sub-expressions. This is what I'm doing when I call 'evaluate()' on each string either side of the '+'

Hope this helps,

David.