public class Counter {
/** uses recursive algorithms to calculate the formula in parentheses and then recursively
* @param args
*/
public static void calculator (String str) {
System.out.println (str);
Load to StringBuffer boost efficiency
StringBuffer cstr= new StringBuffer (str);
To group the remaining symbols and numbers in a formula with a regular
Pattern P=pattern.compile ("\\-?[ 0-9]+ (\\.[ 0-9]+)? | [*/]");
if (Cstr.length () ==0) System.out.println ("Enter the formula");
Find the coordinates of the last parenthesis
int Start=cstr.lastindexof ("(");
Does the traitor formula still have parentheses?
if (start!=-1) {
int End=cstr.indexof (")", start);
StringBuffer spstr=new StringBuffer (cstr.subsequence (start+1, end));
Delete the basic formula in the truncated brackets
Cstr=cstr.delete (start, end+1);
Regular match
Matcher m =p.matcher (SPSTR);
List numlist=new ArrayList ();
Add the value of the basic formula and the multiplication symbol to the group
while (M.find ()) {
Numlist.add (M.group ());
}
Call the calculation method and return the result
StringBuffer Str1=count (numlist);
Insert the result into the specified position
Cstr=cstr.insert (start, str1);
}else{
Calculate the basic formula without parentheses for the last time and print the final result
Matcher m =p.matcher (CStr);
List numlist=new ArrayList ();
while (M.find ()) {
Numlist.add (M.group ());
}
StringBuffer Str1=count (numlist);
System.out.println (STR1);
Return
}
Recursive arrays
System.out.println (CStr);
Calculator (new String (CStr));
}
/**
*
* @param list receive the base formula array
* @return return the computed result string
*/
private static StringBuffer count (List list) {
// system.out.println (list);
double num = 0;
for (int i = 0; i < list.size (); i++) {
if (List.get (i). Equals ("*") | | List.get (i). Equals ("/")) {
Double d=list.get (i). Equals ("*")? Double.parsedouble (String) list.get (i-1)) *double.parsedouble ((String) list.get (i+1)):D ouble.parsedouble ((string ) List.get (i-1))/double.parsedouble ((String) List.get (i+1));
list.add (i-1, d+ ""); List.remove (i); List.remove (i); List.remove (i);
i=i-1;
}
}
for (int i = 0; i < list.size (); i++) {
num+=double.parsedouble ((String) list.ge T (i));
}
return new StringBuffer (num+ "");
}
public static void Main (string[] args) {
Calculator ("3+2+ ((5-6) * ( -3+3/2)/2)");
}
}
Java Four Hybrid Computing calculator