Evaluate the expression. A string is composed of '+', '-', and '0'-'9', and '+' and '-' are binary only.
Operator.
Code:
/**
* Expression evaluate. A string consists of '+', '-', and '0'-'9'. <br>
* And '+' and '-' are binary operators only.
*
* @ Author Administrator
*
*/
Public class calculate {
Public Boolean calculate (string exp ){
Int result = 0;
Char [] chararray = exp. tochararray ();
Int anumber = 0;
Boolean first = true;
Char lastop = '+ ';
For (INT I = 0; I <chararray. length; I ++ ){
Switch (chararray [I]) {
Case '+ ':
Case '-':
If (first ){
Result = anumber;
First = false;
} Else {
If (lastop = '+ '){
Result + = anumber;
} Else {
Result-= anumber;
}
}
Lastop = chararray [I];
ANumber = 0;
Break;
Default:
If (! Character. isdigit (chararray [I]) {
Return false;
}
ANumber * = 10;
ANumber + = (chararray [I]-'0 ');
Break;
}
If (I = chararray. Length-1 ){
If (lastop = '+ '){
Result + = anumber;
} Else {
Result-= anumber;
}
}
}
System. Out. println (result );
Return true;
}
Public static void main (string [] ARGs ){
Calculate c = new calculate ();
C. Calculate ("10-3-3 + 3-9 + 23 ");
}
}