aspose file tools*
The moose likes Java in General and the fly likes Equation and the corresponding result Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Equation and the corresponding result" Watch "Equation and the corresponding result" New topic
Author

Equation and the corresponding result

Surya Bahadur
Ranch Hand

Joined: Sep 28, 2000
Posts: 88
Hi
Assume that i have two variables

int x1 = 5
int x2 = 10;
and i want to get the result of x1+x2 and store the value in one more int variable x3.So basically i would have
int x3 = x1+x2;
But the problem is the equation x1+x2 or x1*x2 or x1/x2 etc is known to the program only at run time that is the user enters that input.
How do i do this in java like change the equation of x3 based on the user input.Any kind of help would be greatly appreciated.Thanks.
Surya
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
You will have to build your own parser, which can take an input string like "5+10" or "6*3", and parse each token, obtaining operands and operators, then apply semantic logic to process those operators and operands - you're basically building a mini-grammar.
If your input strings are very simple, you can just hack something together using a StringTokenizer, looking for a number followed by a math symbol (+,-,/,*) and then another number; if you use an int code to signify the operator then you can write a switch statment to do the actual calculation. For example, say you can parse out the numbers 5 and 10, and the operator "+". Then your logic would be:
int op1 = getOp1(); //5
int op2 = getOp2(); //10
int operator = getOperator(); //let 1 = "+"
int result;
switch(operator){
case 1: result = op1 + op2;
case 2: result = op1 - op2;
case 3: result = op1 * op2;
case 4: result = op1 / op2;
}
For more complicated input strings, you'll have to read up on compiler/parser theory and build your own grammar. There's a book called "Building a parser in java" that might help you.
Good luck!
[ March 10, 2002: Message edited by: Rob Ross ]
[ March 10, 2002: Message edited by: Rob Ross ]

Rob
SCJP 1.4
Surya Bahadur
Ranch Hand

Joined: Sep 28, 2000
Posts: 88
Hi Rob
Thanks a lot for the input it was really useful,but i think i need to indeed write some parser.Let's see how it works out.
Surya
Michael Yuan
author
Ranch Hand

Joined: Mar 07, 2002
Posts: 1427
I think you could use some dynamic code generation. Have a look at my friend Norman's article on this issue's JDJ:
http://www.sys-con.com/java/articleprint.cfm?id=1307


Seam Framework: http://www.amazon.com/exec/obidos/ASIN/0137129394/mobileenterpr-20/
Ringful: http://www.ringful.com/
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Equation and the corresponding result