-2

I have a Java project which required to extract mathematical equation from bunch of code that entered by users. For example, the user has keyed in the following code in the jTextArea:

public void setTest(int i)
{
    int j;
    j=i+i;
}

So, how do I can get the equation of:

j=i+i;

from the above user input since it is in form of String?

Soma
  • 861
  • 2
  • 17
  • 32
yuan
  • 3
  • 1
  • possible duplicate of [Java: Parse a mathematical expression given as a string and return a number](http://stackoverflow.com/questions/1432245/java-parse-a-mathematical-expression-given-as-a-string-and-return-a-number) – Behe Jan 12 '14 at 17:03

2 Answers2

1

You would do this with Java interpreters. See this previous SO question.

How to parse a mathematical expression given as a string and return a number?

Community
  • 1
  • 1
mjkaufer
  • 4,047
  • 5
  • 27
  • 55
  • thanks for the useful info, but since the jTextArea was input by users, i was worry that beanshell is not capable to interpret it. So is there any possible way to just get the equation by ignoring the `code`public void setTest(int i) { int j; `code` – yuan Jan 13 '14 at 01:36
  • Can you try clarifying a bit more? – mjkaufer Jan 13 '14 at 01:38
  • In that program, I was prompt a jTextArea for user input their code for unit testing. However, each programmer has their own coding style and there are many uncertainties. In this case, I am thinking to just get the keyword among the code such as j=i+i; , square = a*b; , etc....So that interpreter can interpret exactly on the equation only. – yuan Jan 13 '14 at 01:42
0

You need to write or find a parser that understands Java -- or at least understands Java well enough to recognize where statements start and end, and then recognize which statements are "equations".

(It isn't an equation. It's an assignment statement. That's an important distinction when the same variable appears on both sides of the = operator, among other reasons.)

keshlam
  • 7,931
  • 2
  • 19
  • 33