中缀表达式实现多位数的计算
代码实现:
public class Calculatordemo {
public static void main(String[] args) {
//数栈
ArrayStack2 numStack = new ArrayStack2(50);
//符号栈
ArrayStack2 operStack = new ArrayStack2(50);
String expresion="70*2*2-5+1-5+3-4";
int num1=0;
int num2=0;
int index=0;
int res1=0;
String keepNum="";
while (true){
//遍历表达式
char c = expresion.substring(index, index + 1).charAt(0);
//判断是否为符号
if (ArrayStack2.isOper(c)){
//符号栈为空直接入栈
if (operStack.isEmpty()){
operStack.push(c);
}else {
//不为空着比较栈顶元素得优先级,小于等于着取出两个数计算
if (ArrayStack2.priority(c)<=ArrayStack2.priority((char) operStack.show())){
num1=numStack.pop();
num2=numStack.pop();
char ch=(char) operStack.pop();
res1=ArrayStack2.cal(num1,num2,ch);
numStack.push(res1);
operStack.push(c);
}
//否则直接入符号栈
else {
operStack.push(c);
}
}
}
//如果是数字直接入数栈
else {
//处理多为数字
keepNum+=c;
//如果是最后以为,着直接入栈
if (index==expresion.length()-1){
numStack.push(Integer.parseInt(keepNum));
}
else {
if (ArrayStack2.isOper(expresion.substring(index+1,index+2).charAt(0))){
numStack.push(Integer.parseInt(keepNum));
keepNum="";
}
}
}
index++;
if (index>=expresion.length()){
break;
}
}
//表达式扫描完后就顺序的从数栈和符号栈中pop出相应的数字和符号并运行
while (true){
if (operStack.isEmpty()){
break;
}
num1=numStack.pop();
num2=numStack.pop();
char ch=(char) operStack.pop();
res1=ArrayStack2.cal(num1,num2,ch);
numStack.push(res1);
}
System.out.println("结果为:"+numStack.pop());
}
}
class ArrayStack2{
private int Maxsize;
private int[] stack;
private int top;
public ArrayStack2(int Maxsize){
this.Maxsize=Maxsize;
stack=new int[Maxsize];
top=-1;
}
//判断是否为空
public boolean isEmpty(){
return top==-1;
}
//判断栈是否以满
public boolean isFull(){
return top==Maxsize-1;
}
//返回栈顶元素
public int show(){
return stack[top];
}
//入栈
public void push(int value){
if (top==Maxsize-1){
System.out.println("栈已经满了");
}
top++;
stack[top]=value;
}
//出栈
public int pop(){
if (top==-1){
System.out.println("栈已空");
}
int value=stack[top];
top--;
return value;
}
public void showList(){
while (true){
if (top==-1){
break;
}
System.out.println(stack[top]);
top--;
}
}
//获取符号优先级
public static int priority(char oper){
if (oper=='*'||oper=='/'){
return 1;
}else if (oper=='+'||oper=='-'){
return 0;
}
else {
return -1;
}
}
//判断是不是一个符号
public static boolean isOper(char val){
return val=='+'||val=='-'||val=='*'||val=='/';
}
//计算方法
public static int cal(int num1,int num2,char oper){
int res=0;
switch (oper){
case '+':
res=num1+num2;
break;
//注意应该用后出来的减去前面出来的数字
case '-':
res=num2-num1;
break;
case '*':
res=num1*num2;
break;
case '/':
res=num1/num2;
break;
default:
throw new RuntimeException("异常");
}
return res;
}
}