栈实现计算器
思路:
利用数组模拟出栈的基本结构
创建两个栈分别存放数字和符号
创建一个指针变量遍历字符串
判断遍历到的字符是数字还是符号(注意转换成数字要减去48,因为它默认会是char类型的1转成int类型)
如果是数字直接入栈,也可以判断栈是否已满,在入栈
如果是字符,自定义字符级别,判断字符级别是多少。如果大于字符栈栈底的字符,就直接加入。反之取出数字栈的两个数字,再从字符栈取出一个字符(因为栈是先进先出,所以要注意运算顺序)进行运算
所有字符遍历完毕,进入一个循环。终止条件是数字栈只有一个或者字符栈为空。每次取出两个数字和一个字符进行运算。最后栈底的数字即为最终结果。
public class StackCalce {
public static void main(String[] args) {
String str = "80*2-6+4";
Stack stack = new Stack(10);
int i = stack.jisuanNumber(str);
System.out.println("结果是"+i);
}
}
class Stack {
public int top;
public int bottom;
public Object stackList[];
public int max;
public Stack(int max) {
this.stackList = new Object[max];
this.top = -1;
this.bottom = -1;
this.max = max;
}
public boolean isnull() {
return top == -1;
}
public boolean isfull() {
return top == max - 1;
}
public void push(Object obj) {
if (isfull()) {
System.out.println("栈满,无法加入");
return;
}
top++;
stackList[top] = obj;
System.out.println("加入成功");
}
public Object pop() {
if (isnull()) {
System.out.println("栈空,无法删除");
}
Object obj = stackList[top];
stackList[top] = null;
top--;
return obj;
}
public Object peek() {
return stackList[top];
}
public void show() {
int temp = top;
if (isnull()) {
System.out.println("栈空,无法查看");
return;
}
while (true) {
if (temp == -1) {
break;
}
System.out.println(stackList[temp]);
temp--;
}
}
public int dengji(char fuhao) {
if (fuhao == '=' || fuhao == '-') {
return 0;
} else if (fuhao == '*' || fuhao == '/') {
return 1;
} else {
return -1;
}
}
public boolean isfuhao(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
public int add(int number1, int number2, char fuhao) {
switch (fuhao) {
case '+':
return number1 + number2;
case '-':
return number1 - number2;
case '*':
return number1 * number2;
case '/':
return number1 / number2;
}
throw new RuntimeException("非法参数");
}
public int jisuanNumber(String str) {
Stack shuzi = new Stack(10);
Stack fuhao = new Stack(10);
String numb = "";
for (int i = 0; i < str.length(); i++) {
if (isfuhao((char) str.codePointAt(i))) {
var fu = (char) str.codePointAt(i);
if (fuhao.isnull()) {
fuhao.push(fu);
} else if (dengji(fu) <= dengji((char) fuhao.peek())) {
int number1 = (int) shuzi.pop();
int number2 = (int) shuzi.pop();
shuzi.push(add(number2, number1, (char) fuhao.pop()));
fuhao.push(fu);
} else {
fuhao.push(fu);
}
} else {
if(i == str.length()-1){
shuzi.push((int) str.codePointAt(i)-48);
}
else {
numb += String.valueOf((int) str.codePointAt(i)-48);
if(isfuhao((char) str.codePointAt(i+1))){
shuzi.push(Integer.parseInt(numb));
numb = "";
}else {
shuzi.push(Integer.parseInt(numb));
}
}
}
}
while (true) {
if (fuhao.isnull()) {
break;
}
int num = (int) shuzi.pop();
int num2 = (int) shuzi.pop();
char fu = (char) fuhao.pop();
int add = add(num, num2, fu);
shuzi.push(add);
}
return (int) shuzi.pop();
}
}