//参照严的数据结构教材,逻辑简单
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
public class Calculator {
private static char precede[][] = new char[256][256];
private static Set<Character> testifiedOperator = new HashSet<Character>();
static
{
testifiedOperator.add('+');
testifiedOperator.add('-');
testifiedOperator.add('*');
testifiedOperator.add('/');
testifiedOperator.add('(');
testifiedOperator.add(')');
testifiedOperator.add('#');
precede['+']['+'] = '>';
precede['+']['-'] = '>';
precede['+']['*'] = '<';
precede['+']['/'] = '<';
precede['+']['('] = '<';
precede['+'][')'] = '>';
precede['+']['#'] = '>';
precede['-']['+'] = '>';
precede['-']['-'] = '>';
precede['-']['*'] = '<';
precede['-']['/'] = '<';
precede['-']['('] = '<';
precede['-'][')'] = '>';
precede['-']['#'] = '>';
precede['*']['+'] = '>';
precede['*']['-'] = '>';
precede['*']['*'] = '>';
precede['*']['/'] = '>';
precede['*']['('] = '<';
precede['*'][')'] = '>';
precede['*']['#'] = '>';
precede['/']['+'] = '>';
precede['/']['-'] = '>';
precede['/']['*'] = '>';
precede['/']['/'] = '>';
precede['/']['('] = '<';
precede['/'][')'] = '>';
precede['/']['#'] = '>';
precede['(']['+'] = '<';
precede['(']['-'] = '<';
precede['(']['*'] = '<';
precede['(']['/'] = '<';
precede['(']['('] = '<';
precede['('][')'] = '=';
precede['#']['+'] = '<';
precede['#']['-'] = '<';
precede['#']['*'] = '<';
precede['#']['/'] = '<';
precede['#']['('] = '<';
precede['#']['#'] = '=';
}
//进行操作运算符
private static double operate(double a,double b,char op)
{
double result = 0.0;
switch (op) {
case '*':
result = a * b;
break;
case '/':
result = a * 1.0 / b;
break;
case '+':
result = a + b;
break;
case '-':
result = a -b;
break;
default:
break;
}
return result;
}
public static void execute(String expreesion)
{
String ex = expreesion + "#";
int index = 0;
Stack<Double> OPND = new Stack<Double>();
Stack<Character> OPTR = new Stack<Character>();
OPTR.push('#');
while(index < ex.length())
{
if(ex.charAt(index) >= '0' && ex.charAt(index) <= '9' )
{
int num = 0;
while(index < ex.length()&&ex.charAt(index) >= '0' && ex.charAt(index) <= '9')
{
num = num * 10 + (ex.charAt(index) - '0');
index++;
}
OPND.push(num * 1.0);
}else
{
if(!testifiedOperator.contains(ex.charAt(index)))
{
//
throw new NumberFormatException("包含非法字符");
}
switch (precede[OPTR.peek()][ex.charAt(index)]) {
case '<':
OPTR.push(ex.charAt(index));
index++;
break;
case '=':
OPTR.pop();
index++;
break;
case '>':
if(OPND.size() < 2)
throw new NumberFormatException("表达式非法");
double numb = OPND.pop();
double numa = OPND.pop();
double result = operate(numa, numb, OPTR.pop());
OPND.push(result);
break;
default:
throw new NumberFormatException("表达式非法");
}
}
}
System.out.println(OPND.pop());
}
public static void main(String[] args) {
String expreesion = "32*32/(2+6)-129";
Calculator.execute(expreesion);
}
}
java版简易计算器代码易懂(原创)
最新推荐文章于 2024-05-13 04:14:52 发布