Java string formula calculation --- reprint

Source: Internet
Author: User
Import java. Lang. Reflect. method;
Import java. util. arraylist;
Import java. util. hashmap;
Import java. util. List;
Import java. util. Map;
/**
* A string expression can be computed simply by using functions.
* @ Author
*/
Public class analyzecalculate {
/**
* Defining Operators
*/
Public static list <string> lc = new arraylist <string> ();
Static {
LC. Add ("+ ");
LC. Add ("'");
LC. Add ("*");
LC. Add ("/");
}
/**
* Define logical operators
*/
Public static list <string> lj = new arraylist <string> ();
Static {
LJ. Add ("> ");
LJ. Add ("<");
LJ. Add ("= ");
LJ. Add ("! ");
}
/**
* Int array comment, first identifier: 0 built-in function 1 custom function; second identifier: number of parameters
*/
Public static Map <string, int []> funmap = new hashmap <string, int []> ();
Static {
// Built-in function, which can be reflected
Funmap. Put ("ABS", new int [] {0, 1 });
Funmap. Put ("ACOs", new int [] {0, 1 });
Funmap. Put ("asin", new int [] {0, 1 });
Funmap. Put ("atan", new int [] {0, 1 });
Funmap. Put ("cbrt", new int [] {0, 1 });
Funmap. Put ("Ceil", new int [] {0, 1 });
Funmap. Put ("Cos", new int [] {0, 1 });
Funmap. Put ("cosh", new int [] {0, 1 });
Funmap. Put ("exp", new int [] {0, 1 });
Funmap. Put ("expm1", new int [] {0, 1 });
Funmap. Put ("floor", new int [] {0, 1 });
Funmap. Put ("log", new int [] {0, 1 });
Funmap. Put ("log10", new int [] {0, 1 });
Funmap. Put ("log1p", new int [] {0, 1 });
Funmap. Put ("random", new int [] {0, 1 });
Funmap. Put ("RINT", new int [] {0, 1 });
Funmap. Put ("round", new int [] {0, 1 });
Funmap. Put ("SIGNUM", new int [] {0, 1 });
Funmap. Put ("sin", new int [] {0, 1 });
Funmap. Put ("Sinh", new int [] {0, 1 });
Funmap. Put ("SQRT", new int [] {0, 1 });
Funmap. Put ("Tan", new int [] {0, 1 });
Funmap. Put ("Tanh", new int [] {0, 1 });
Funmap. Put ("Max", new int [] {0, 2 });
Funmap. Put ("min", new int [] {0, 2 });
// User-Defined Functions
Funmap. Put ("if", new int [] {1, 3 });
Funmap. Put ("Mod", new int [] {1, 2 });
Funmap. Put ("int", new int [] {1, 1 });
}

/**
* Formula initialization and conversion
*
* @ Param Str
* @ Return indicates the processed computing client string.
*/
Public static string strcast (string Str ){
STR = Str. tolowercase (); // remove spaces and write less

If (STR = NULL? True: Str. Length () = 0)
Return "0 ";
If (! Checkformula (STR ))
Return "0 ";
STR = Str. replaceall ("\\*-","**");
STR = Str. replaceall ("-\\*","**");
STR = Str. replaceall ("/-","//");
STR = Str. replaceall ("-/","//");
STR = Str. replaceall ("\\+ -","-");
STR = Str. replaceall ("-\ + ","-");
STR = Str. replaceall ("-","'");
STR = Str. replaceall ("\\*\\*","*-");
STR = Str. replaceall ("//","/-");
STR = Str. replaceall ("","");
Return STR;
}

/**
* Check whether the number of parentheses in the formula is correct.
*
* @ Param formulastr
* @ Return indicates whether parentheses in the formula are paired.
*/
Public static Boolean checkformula (string formulastr ){
Boolean flag = true;
Int COUNT = 0;
For (INT I = 0; I <formulastr. Length (); I ++ ){
String S = string. valueof (formulastr. charat (I ));
If ("(". Equals (s ))
Count ++;
Else if (")". Equals (s ))
Count --;
}
Flag = COUNT = 0;
Return flag;
}

/**
* Split Functions
*
* @ Param Str
* @ Param BS
* @ Return refers to the split string.
*/
Public static string [] splitefun (string STR, string BS ){
List <string> List = new arraylist <string> ();
String BDS = "";
Int bracket = 0;
Int Len = Str. Length ();
For (INT I = 0; I <Len; I ++ ){
String S = string. valueof (Str. charat (I ));
If ("(". Equals (s )){
Bracket ++;
} Else if (")". Equals (s )){
Bracket --;
}

If (bracket = 0 & BS. Equals (s )){
List. Add (BDS );
BDS = "";
Continue;
}

BDS + = s;
}

List. Add (BDS );

String [] Ss = new string [list. Size ()];
For (INT I = 0; I <list. Size (); I ++ ){
Ss [I] = list. Get (I );
}

Return SS;
}

/**
* User-Defined Functions
*
* @ Param Str
* @ Param funstr
* @ Return process user-defined functions
*/
Public static string customfun (string STR, string funstr ){
String reval = "0 ";

String [] GSS = splitefun (STR ,",");
If ("if". Equals (funstr )){
If (compare (GSS [0]) {
Reval = calculate (GSS [1]);
} Else {
Reval = calculate (GSS [2]);
}
} Else if ("Mod". Equals (funstr )){
Double D2 = new double (calculate (GSS [1]);
If (d2 = 0)
Return reval;
Double d1 = new double (calculate (GSS [0]);
Reval = (d1% D2) + "";
} Else if ("int". Equals (funstr )){
Reval = math. Floor (New Double (calculate (GSS [0]) + "";
}
Return reval;
}

/**
* Logical expression judgment
* @ Param Str
* @ Return true or false
*/
Public static Boolean compare (string Str ){
Boolean flag = false;
Boolean BS = false;
Int Len = Str. Length ();
Int bracket = 0;
String ljbds = "";
Double d_left = 0;
Double d_right = 0;

For (INT I = 0; I <Len; I ++ ){
String S = string. valueof (Str. charat (I ));
If ("(". Equals (s )){
Bracket ++;
} Else if (")". Equals (s )){
Bracket --;
}

If (bracket = 0 & LJ. Contains (s )){
For (Int J = I; j <Len; j ++ ){
String Ts = string. valueof (Str. charat (j ));
If (LJ. Contains (TS )){
Ljbds + = ts;
} Else {
BS = true;
Break;
}
}
}
If (BS)
Break;
}

String [] S = Str. Split (ljbds );
D_left = new double (calculate (s [0]);
D_right = new double (calculate (s [1]);

If ("<". Equals (ljbds )){
If (d_left <d_right)
Return true;
} Else if (">". Equals (ljbds )){
If (d_left> d_right)
Return true;
} Else if ("=". Equals (ljbds )){
If (d_left = d_right)
Return true;
} Else if ("> =". Equals (ljbds )){
If (d_left> = d_right)
Return true;
} Else if ("<=". Equals (ljbds )){
If (d_left <= d_right)
Return true;
} Else if ("<>". Equals (ljbds) | "! = ". Equals (ljbds )){
If (d_left! = D_right)
Return true;
}

Return flag;
}

/**
* Recursive call operation
*
* @ Param Str
* @ Return string
*/
Public static string calculate (string Str ){

String reval = "";
String BDS = "";
Int bracket = 0; // Number of parentheses
Int Pos = 0;
Boolean Title = false;

If (Str. substring (0, 1). Equals ("'")){
STR = Str. substring (1 );
Title = true;
}

Int Len = Str. Length ();

For (INT I = 0; I <Len; I ++ ){
String S = string. valueof (Str. charat (I ));
Pos = I;
Bracket = 0;
If (! LC. Contains (s) {// if no operator is encountered
If ("(". Equals (s) {// if left parentheses are encountered
If (funmap. containskey (BDS) {// If the left bracket is a function
For (Int J = I + 1; j <Len; j ++) {// starts the loop after the left parenthesis
Pos ++; // Accumulative number of characters to be moved
String Ts = string. valueof (Str. charat (j); // a single character
// Reval + = ts;
If ("(". Equals (TS) // if it is left parenthesis cumulative
Bracket ++;
Else if (")". Equals (TS) {// if it is a right brace, reduce it.
Bracket --;
If (bracket =-1) {// if it is-1, the end of the brackets
Reval = reval. substring (0, Reval. Length ()
-BDS. Length (); // obtain the expression that removes the function header again.
Reval + = funcalculate (Str. substring (I + 1,
J), BDS); // Add the function result to the expression to form a new expression.
I = Pos; // the counter is added.
BDS = ""; // clear the function Header
Break; // exit this cycle
}
}
}
} Else {// for normal operations
For (Int J = I + 1; j <Len; j ++ ){
Pos ++;
String Ts = string. valueof (Str. charat (j ));
If ("(". Equals (TS ))
Bracket ++;
Else if (")". Equals (TS )){
Bracket --;
If (bracket =-1 ){
Reval + = calculate (Str
. Substring (I + 1, POS ));
I = Pos;
BDS = "";
Break;
}
}
}
}
} Else {// sum of the total expression and the number of the last operation (or function)
BDS + = s;
Reval + = s;
}
} Else {// the last number (or function) of the operator is cleared.
BDS = "";
Reval + = s;
}
}

If (title)
Reval = "-" + reval;
Return szys (reval );
}

/**
* Function operations
*
* @ Param GS
* @ Param flag
* @ Return string
*/
Public static string funcalculate (string Gs, string funstr ){
String rval = "0 ";
If (funmap. containskey (funstr )){
Int [] CSI = funmap. Get (funstr );
Try {
If (CSI [0] = 0) {// Java internal function, called through reflection
Class [] cs = new class [CSI [1];
Object [] objs = new object [CSI [1];
String [] GSS = zlcs (GS );
For (INT I = 0; I <CSI [1]; I ++ ){
CS [I] = double. Class;
Objs [I] = new double (calculate (GSS [I]);
}
Class CLS = Class. forname ("Java. Lang. Math ");
Method M = Cls. getmethod ("ABS", CS );
Rval = string. valueof (M. Invoke (CLS, objs ));
} Else if (CSI [0] = 1) {// User-Defined Function
Rval = customfun (GS, funstr );
}
} Catch (exception e ){

}
}

Return rval;
}

/**
* Parameter segmentation in the formula
* @ Param Str
* @ Return string []
*/
Public static string [] zlcs (string Str ){
Int Len = Str. Length ();
Boolean flag = true;
String tstr = "";

For (INT I = 0; I <Len; I ++ ){
String S = string. valueof (Str. charat (I ));
If ("(". Equals (s )){
Flag = false;
} Else if (")". Equals (s )){
Flag = true;
}
If (flag & ",". Equals (s )){
Tstr + = "@";
} Else {
Tstr + = s;
}
}

Return tstr. Split ("@");

}

/**
* Four arithmetic expressions
*
* @ Param Str
* @ Return string
*/
Public static string szys (string GS ){
GS = GS + "+ 0"; // because the following computation is performed only when a symbol is encountered, adding one more computation symbol does not affect the value.
String C1 = ""; // The First operator number
String C2 = ""; // The second operator number.
String S1 = ""; // number of the first operation
String S2 = ""; // The second operation count.
String S3 = ""; // The third operation count.

Int Len = Gs. Length ();
For (INT I = 0; I <Len; I ++ ){
String S = string. valueof (Gs. charat (I); // obtain the character at this position and convert it to a string for comparison.

If (LC. Contains (s) {// if it is an operator number
If (c1.length () = 0) // if the first operator is null, add
C1 = s;
Else if (c2.length () = 0) {// otherwise, if the second operator is null, add
C2 = s; // The second operator number.
If ("+". Equals (C2) | "'". Equals (C2) {// if the level of the second operator is low, the calculation is performed.
S1 = _ 4zys (S1, C1, S2); // calculate the first and second numbers
C1 = c2; // Save the second operator. The other operator is null.
C2 = "";
S2 = "";
}
} Else {// all the above are saved
If ("+". Equals (s) | "'". Equals (s) {// if the third operator is low, perform operations
S2 = _ 4zys (S2, C2, S3); // calculate the number of the second three and save it to the second one.
S1 = _ 4zys (S1, C1, S2); // calculate the first two and save it to the first one.
C1 = s; // Save the current operator. Other values are empty.
S2 = "";
C2 = "";
S3 = "";
} Else {// if the third operator is of a high level
S2 = _ 4zys (S2, C2, S3); // calculate the number of the second three and save it to the second one.
C2 = s; // the operator is not moved.
S3 = "";
}
}
} Else if (s1.length ()> 0 & c1.length ()> 0 & c2.length () = 0) {// if the first number is, the first operator is saved, the second operator is not saved. The second operator is saved.
S2 + = s;
} Else if (c1.length () = 0) {// if no operator exists, save the first number
S1 + = s;
} Else if (s1.length ()> 0 & s2.length ()> 0 & c1.length ()> 0
& C2.length ()> 0) {// if both the first and second numbers and operators exist, save the third number
S3 + = s;
}
}
Return S1;
}

/**
* Four basic arithmetic operations
*
* @ Param C1
* Operation count 1
* @ Param S1
* Operator (addition, subtraction, multiplication, division)
* @ Param C2
* Operation count 2
* @ Return string
*/
Public static string _ 4zys (string C1, string S1, string C2 ){
String reval = "0 ";

Try {
Double Ln = double. valueof (C1). doublevalue ();
Double Rn = double. valueof (C2). doublevalue ();
If ("+". Equals (S1 )){
Return (LN + rn) + "";
} Else if ("'". Equals (S1 )){
Return (Ln-Rn) + "";
} Else if ("*". Equals (S1 )){
Return (LN * rn) + "";
} Else if ("/". Equals (S1 )){
If (Rn = 0)
Return reval;
Else
Return (Ln/RN) + "";
}
} Catch (exception e ){
} Finally {
}

Return reval;
}

/**
* Test
* @ Param ARGs
*/
Public static void main (string [] ARGs ){

String GS = "If (4> 3, if (2-1)/(0.0001) * 3> 3, (2-(2-1)/(0.0001) * 3) * 0.8, 0), (2 + (3-2)/(0.0001) * 1) * 1 )";
// Perform four arithmetic operations to obtain the result
System. Out. println (szys (strcast ("3-4 *-5 + 5 ")));
System. Out. println (calculate (strcast ("3-4 *-5 + 5 ")));
// Function operation result
System. Out
. Println (calculate (strcast ("3 + ABS (mod (4, if (2> 3, 1, 3)-ABS (2*4 )) * 5 + 5 ")));

System. Out. println (calculate (strcast ("If (0.0*2> = 10.0, 0, 10.0-0.0*2 )")));

System. Out. println (calculate (strcast ("If (0 <2, (10.0-0*5) * 0.8, 0 )")));

System. Out. println (calculate (strcast ("-10/0 ")));

}

}

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.