简单计算器的实现:给定一个字符串表达式:“7+62-42”,计算出结果
1.创建两个栈:numStack(数字栈),operateStack(操作符栈)
2.将字符串转换为char数组,创建while循环,结束条件是index==char数组.length。
定义index表示处理到哪个位置了
2.1如果是数字
StringBuffer sb = new StringBuffer();
int temp = index;
2.1.1创建while循环,结束条件是temp下标的字符是操作符
sb.append(char数组[temp]);
temp++;
2.1.2
int val = Integer.valueOf(sb.toString())
push(val)->numStack,index = temp
2.2如果是符号
2.2.1如果operateStack为空 或者 当前符号的优先级大于operateStack顶部符号的优先级
将该符号push->opeateStack
index++
2.2.2如果当前符号的优先级 小于等于 operateStack顶部符号的优先级
pop出numStack两个数字和pop出operateStack一个符号进行运算,将结果push->numStack
3.创建while循环,结束条件是operateStack为空
3.1从numStack中pop两个数字,从operateStack中pop出一个符号
3.2进行运算,运算结果push->numStack
4.输出 pop->numStack
import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack numStack = new ArrayStack(1000);
ArrayStack operateStack = new ArrayStack(1000);
Scanner scanner = new Scanner(System.in);
System.out.println("请输入表达式(仅含+-*/和数字):");
String expStr= scanner.next();
char[] expArr = expStr.toCharArray();
int index = 0;
while (index != expArr.length){
if (!ArrayStack.isOperate(expArr[index])){
StringBuilder sb = new StringBuilder();
int temp = index;
while (!ArrayStack.isOperate(expArr[temp])){
sb.append(expArr[temp]);
temp++;
if (temp==expArr.length)break;
}
index = temp;
int val = Integer.parseInt(sb.toString());
numStack.push(val);
}else{
if (operateStack.isEmpty()
|| (ArrayStack.getPriority(expArr[index]) > ArrayStack.getPriority((char) operateStack.peek()))){
operateStack.push(expArr[index]);index++;
}else {
int num1 = numStack.pop();
int num2 = numStack.pop();
char operate = (char) operateStack.pop();
int res = ArrayStack.calculate(num2,operate,num1);
numStack.push(res);
}
}
}
while (!operateStack.isEmpty()){
int num1 = numStack.pop();
int num2 = numStack.pop();
char operate = (char) operateStack.pop();
int res = ArrayStack.calculate(num2,operate,num1);
numStack.push(res);
}
System.out.println(numStack.pop());
}
}
class ArrayStack{
public int maxSize;
public int top;
public int[] stack;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
this.stack = new int[maxSize];
top = -1;
}
public boolean isFull(){return top==maxSize-1;}
public boolean isEmpty(){return top==-1;}
public void push(int val){
if (isFull()) System.out.println("The stack is full!");
else stack[++top] = val;
}
public int pop(){
if (isEmpty()) {
System.out.println("The stack is Empty!");
return -9999;
}
return stack[top--];
}
public int peek(){return stack[top];}
public static boolean isOperate(char c){return c == '+' ||c == '-' ||c == '*' ||c == '/' ;}
public static int getPriority(char c){
if (c == '+' || c == '-')return 0;
return 1;
}
public static int calculate(int num1,char operate,int num2){
int res = 0;
switch (operate){
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
}
return res;
}
}