Package com.malakana.cal;
Import Android.annotation.SuppressLint;
Import java.util.*;
public class Yunsuan {
Yunsuan (String str1) {
EvaluateExpression (STR1);
}
@SuppressLint ("usevalueof")
public static string EvaluateExpression (String str) {
Char[] A;
int i = 0;
A = Str.tochararray ();
stack<float> OPND = new stack<float> ();
stack<character> optr = new stack<character> ();
Optr.push (' = ');
float number = 0;
int decimalnum = 1;
Boolean integer = false;
Boolean decimal = false;
while (true) {
if (i = = Str.length ())
Break
if (in (a[i]) = =-1) {
Number = number * + (A[i]-48);
Integer = true;
if (decimal)
Decimalnum = Decimalnum * 10;
i++;
} else if (a[i] = = '. ') {
if (decimal)
return "ERROR";
decimal = integer = true;
i++;
} else if (in (A[i]) >-1 && in (A[i]) < 7) {
if (in (a[i]) = = 1 && (i = = 0 | | In (a[i-1]) = = 4))
Opnd.push (new Float (0));
if (integer) {
Opnd.push (New Float (Number/decimalnum));
Number = 0;
Decimalnum = 1;
Integer = decimal = false;
}
Switch (Precede (in (Optr.peek ()), in (A[i]))) {
Case 2:
if (Opnd.empty ())
return "ERROR";
float x = Opnd.pop ();
if (Opnd.empty ())
return "ERROR";
Float y = opnd.pop ();
Char theta = Optr.pop ();
if (in (theta) = = 3 && x = = 0)
return "ERROR";
Opnd.push (New Float (Operate (y, theta, X)));
Break
Case 1:
Optr.pop ();
i++;
Break
Case 0:
Optr.push (New Character (A[i]));
i++;
Break
Case-1:
return "ERROR";
}
}
}
if (Opnd.empty ())
return "ERROR";
Else
Return ("" + Opnd.peek ());
}
public static int in (char t) {
int i = 0;
if (T > && T < 58)
return-1;
Switch (t) {
Case ' + ':
i = 0;
Break
Case '-':
i = 1;
Break
Case ' * ':
i = 2;
Break
Case '/':
i = 3;
Break
Case ' (':
i = 4;
Break
Case ') ':
i = 5;
Break
Case ' = ':
i = 6;
Break
}
return i;
}
public static int precede (int t1, int t2) {
int relationship[][] = {{2, 2, 0, 0, 0, 2, 2},
{2, 2, 0, 0, 0, 2, 2}, {2, 2, 2, 2, 0, 2, 2},
{2, 2, 2, 2, 0, 2, 2}, {0, 0, 0, 0, 0, 1,-1},
{2, 2, 2, 2,-1, 2, 2}, {0, 0, 0, 0, 0,-1, 1}};
return RELATIONSHIP[T1][T2];
}
public static float Operate (float A, char theta, float b) {
float i = 0;
Switch (theta) {
Case ' + ':
i = a + b;
Break
Case '-':
i = a-B;
Break
Case ' * ':
i = a * b;
Break
Case '/':
i = A/b;
Break
}
return i;
}
public static void Main (string[] args) {
New Yunsuan (NULL);
}
}
Java programming processing arithmetic (including parentheses)