An instance of a Java class that can parse a formula--an expression that can be passed into a numeric operation, an expression containing a variable

Source: Internet
Author: User

A few days ago encountered a problem, you need to read a formula containing parameters from the XML file and call it.

So the internet to find ways, but it is not found can be resolved with parameters of the formula method, and then absorb some of the essence, and on this basis to be transformed, and finally realized, but this efficiency is very low, if who has a better way, hope to share, I am here to be a comment

The test class is at the bottom and can be tested according to your requirements.

You can use this class as a tool class to call only its construction method and the GetResult () method (see the Main method in detail) when other classes call. If you need to use a formula that contains parameters in other classes, you can use the Formula.paras.add ("data to be added") method to store data, which by default is stored in the order in which the data is extracted, that is, the first variable is stored in the first data (see this example), and so on.


The following is the code-------------------------------------------------------------------------------------------------------------------- ---------------------------------------

Import Java.util.Vector;
public class Formula {
private int leftbracket = 0; Number of left parentheses
private int rightbracket = number of 0;//right parentheses
private int startl = position of 0;//left parenthesis
private int startr = 0;//The position of the right parenthesis
Private double answer = 0;
Private String Leftnumber = "0";
Private String Rightnumber = "0";
Public String MSG = "";
Private String formula= "";
Private int[] sym = new Int[4];
Private vector<string> list = new vector<string> ()//for storing characters parsed from strings
Static vector<integer> paras = new vector<integer> ()//To hold variable arguments


/*
* Construction method, with the formula to be calculated as a parameter
*/
Public Formula (String calrule) {
This.setformula (Calrule);
}

/*
* Get the number of left parenthesis
*/
private int Getleftbracket (String calrule) {
Leftbracket = 0;
Startl = Calrule.indexof ("(");
if (Startl!=-1) {
Calrule = calrule.substring (Startl + 1, calrule.length ());
}
while (Startl!=-1) {
leftbracket++;
Startl = Calrule.indexof ("(");
Calrule = calrule.substring (Startl + 1, calrule.length ());
}
return leftbracket;
}


/*
* Format Set
*/
public void Setformula (String calrule) {
Formula=replacesubtration (Calrule.trim ());
Formula= "(" +formula+ ")";
}

/*
* To support negative numbers in the formula, use "'" to indicate a minus sign, use "-" to denote the minus sign, and replace all minus signs with "'"
*/
private string Replacesubtration (string vstr) {
String tmp= "";
String result= "";
int starts = Vstr.indexof ("-");
if (starts!=-1) {
if (Starts > 0) {
TMP = vstr.substring (startS-1, starts);
if (!) + ". Equals (TMP) &&!" -". Equals (TMP) &&!" * ". Equals (TMP) &&!" /". Equals (TMP) &&
!" (". Equals (TMP)) {
result = result + vstr.substring (0, starts) + "'";
}
Else
result = result + vstr.substring (0, starts + 1);
}
Else
result = result + vstr.substring (0, starts + 1);
Vstr = vstr.substring (starts + 1);
}
While (starts!=-1) {
Starts = Vstr.indexof ("-");
if (Starts > 0) {
TMP = vstr.substring (startS-1, starts);
if (!) + ". Equals (TMP) &&!" -". Equals (TMP) &&!" * ". Equals (TMP) &&!" /". Equals (TMP) &&
!" (". Equals (TMP))
result = result + vstr.substring (0, starts) + "'";
Else
result = result + vstr.substring (0, starts + 1);
}
Else
result = result + vstr.substring (0, starts + 1);
Vstr = vstr.substring (starts + 1);
}
RESULT+=VSTR;
return result;
}


Public String Getformula () {
Return Formula.replace (', '-'). Substring (1,formula.length ()-1);
}


/*
* Get right Bracket number
*/
private int Getrightbracket (String calrule) {
Rightbracket = 0;
STARTR = Calrule.indexof (")");
if (Startr!=-1) {
Calrule = calrule.substring (startr + 1, calrule.length ());
}
while (Startr!=-1) {
rightbracket++;
STARTR = Calrule.indexof (")");
Calrule = calrule.substring (startr + 1, calrule.length ());
}
return rightbracket;
}


/*
/* Contrast the left and right bracket number
*/
Private Boolean COMPARETOLR () {
int lb = getleftbracket (formula);
int RB = Getrightbracket (formula);
Boolean CTLR = false;
if (lb = = RB) {
MSG = "";
CTLR = true;
else if (lb > RB) {
MSG = "The number of left parentheses is more than the right bracket, please check." ";
CTLR = false;
} else {
MSG = "The number of left parentheses is less than the right bracket, please check." ";
CTLR = false;
}
return CTLR;
}
/*
/* Check the formula for illegal character Furu (+,-), etc.
*/
Private Boolean Checkformula () {
Boolean isok=true;
String[] Bracket =new string[2];
String[] Sign=new string[4];
Bracket[0]= "(";
Bracket[1]= ")";
sign[0]= "+";
Sign[1]= "'";
sign[2]= "*";
sign[3]= "/";
String vstr= "";
for (int i=0;i<bracket.length;i++) {
for (int j=0;j<sign.length;j++) {
if (i==0)
VSTR=BRACKET[I]+SIGN[J];
Else
Vstr=sign[j]+bracket[i];
if (Formula.indexof (VSTR) >0) {
Msg= "There are illegal characters in the formula" +VSTR;
Isok=false;
return isOk;
}
}
}
for (int i=0;i<sign.length;i++) {
for (int j=0;j<sign.length;j++) {
VSTR=SIGN[I]+SIGN[J];
if (Formula.indexof (VSTR) >0) {
Msg= "There are illegal characters in the formula" +VSTR;
Isok=false;
return isOk;
}
}
}
if (Formula.indexof ("()") >0) {
msg= "the illegal character () exists in the formula;
Isok=false;
}
return isOk;
}

/*
* Determine if the string entered is legitimate
*/
public Boolean checkvalid () {
if ((formula==null) | | (Formula.trim (). Length () <=0)) {
Msg= "Please set property calrule!";
return false;
}
Return (COMPARETOLR () &&checkformula ());
}


/* Return formula execution results
*/
Public double GetResult () {
String formulastr = "", Calrule = "";
Double value = 0.0;
Calrule = This.formula;
if (Checkvalid ()) {
for (int i = 0; i < Leftbracket; i++) {
int Istart=calrule.lastindexof ("(") + 1;
Get the contents in the innermost brackets
Formulastr = calrule.substring (IStart, istart+calrule.substring (IStart). IndexOf (")"). Trim ();
Symbolparse (FORMULASTR);
Value = ParseString ();
Istart=calrule.lastindexof ("(");
int iend=calrule.substring (IStart). IndexOf (")") +1;
Calrule = calrule.substring (0,istart). Trim () +
Value +
Calrule.substring (Istart+iend, Calrule.length ()). Trim ();
}
}
Double tmp = MATH.POW (10, 10);
Value = Math.Round (value * tmp)/tmp;
System.out.println (MSG);
return value;
}
public void Formulastr (String calrule) {
String formulastr = "";
if (Checkvalid ()) {
for (int i = 0; i < Leftbracket; i++) {
Formulastr = calrule.substring (Calrule.lastindexof ("(") + 1, calrule.indexof (")")). Trim ();
Symbolparse (FORMULASTR);
Double value = parsestring ();
String.valueof (value);
System.out.println ("formulastr=" + formulastr);
Formulaval = double.parsedouble (FORMULASTR);
System.out.println ("formulaval=" + value);
Calrule = calrule.substring (0, Calrule.lastindexof ("()). Trim () + value + calrule.substring (Calrule.indexof (") ") + 1, Calrule.length ()). Trim ();
System.out.println ("calrule=" + calrule);
}
}
}


/*
/* Extract final bracket data to list
*/
private void Symbolparse (String str) {
List.clear ();
int count = 0;
for (int i = 0; i < 4; i++) {
Comparemin (str);
while (Sym[i]!=-1) {
String insstr = str.substring (0, Sym[i]). Trim ();
Determine if INSSTR contains letters
if (Containsletter (INSSTR)) {
Insstr = integer.tostring (Parseletter (Insstr, Paras.get (count));
}
List.add (INSSTR);
Insstr = str.substring (Sym[i], sym[i] + 1). Trim ();
List.add (INSSTR);

str = str.substring (Sym[i] + 1, str.length ()). Trim ();
Comparemin (str);
count++;
}
}
if (sym[0] = =-1 && sym[1] = = 1 && sym[2] = = 1 & sym[3] = = 1) {
if (Containsletter (str)) {
str = integer.tostring (Parseletter (str, paras.get (count));
}
List.add (str);
}
}

public boolean containsletter (String insstr) {
Boolean isletter = false;

for (int i=0; i<insstr.length (); i++) {
char ch = insstr.charat (i);
if (Character.isletter (CH)) {
Isletter = true;
}
}
return isletter;
}

public int Parseletter (String insstr, int para) {

if (Insstr.charat (0) = = '-') {
Para = 0-para;
}
return para;
}

/*
/* Loop Compare substring starting value
*/
private void Comparemin (String str) {
int sps = Str.indexof ("'");//Subtraction Subtration
Sym[0] = SPS;
int spa = Str.indexof ("+");/Add addition
SYM[1] = Spa;
int spd = Str.indexof ("/");//Division Division
SYM[2] = SPD;
int SPM = Str.indexof ("*");//multiplication multiplication
SYM[3] = SPM;
for (int i = 1; i < sym.length; i++) {
for (int j = 0; J < Sym.length-i; J + +)
if (Sym[j] > sym[j + 1]) {
int temp = Sym[j];
SYM[J] = sym[j + 1];
Sym[j + 1] = temp;
}
}
}


Private Double parsestring ()
Throws NumberFormatException, Stringindexoutofboundsexception {
try{
Calculate ();
return answer;
}catch (Exception e) {
msg= "Error:" + e.getmessage ();
return 0.0;
}
}


/*
* Calculation
*/
private void Calculate () {
/*
/* Process Division
*/
int spd = List.indexof ("/");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.