package A;
public class JosePhu {
public static void main(String[] args) {
String expression="300+2*6-2";
//你可以画两个表示栈的图
ArrayStack numStack=new ArrayStack(10);//数字栈
ArrayStack operStack=new ArrayStack(10);//符号栈
int index=0;
int num1=0;
int num2=0;
int oper=0;
int res=0;
char ch=‘ ‘;
String keepNum="";
while (true){
//substring能够截取字符串的某一段,取一个之后,它本质上还是一个字符串,所以利用charAt(0),取一个char类型的字符
ch=expression.substring(index,index+1).charAt(0);
if (operStack.isOper(ch)){
if (!operStack.isEmpty()){//这是判断这个栈是不是空的
if (operStack.priority(ch)<=operStack.priority(operStack.peek())){
num1=numStack.pop();
num2=numStack.pop();
oper=operStack.pop();
res=numStack.cal(num1,num2,oper);
numStack.push(res);
operStack.push(ch);
}else {
operStack.push(ch);
}
}else {
operStack.push(ch);
}
}else {
/*
* 就是说这里就是解决一个1+2和10+2的问题,因为它每次只探了一位*/
keepNum=keepNum+ch;
//如果是最后一位,直接压进去就可以了
if (index==expression.length()-1){
numStack.push(Integer.parseInt(keepNum));
}else {
//就是说再往后面探一位
if (operStack.isOper(expression.substring(index+1,index+2).charAt(0))){
//将字符串转为int类型的方法,比如"123"->123
numStack.push(Integer.parseInt(keepNum));
keepNum="";//使用完要将keepNum清空
}
}
}
index++;
if (index>=expression.length()){
break;
}
}
while (true){
if (operStack.isEmpty()){
break;
}
num1=numStack.pop();
num2=numStack.pop();
oper=operStack.pop();
res=numStack.cal(num1,num2,oper);
numStack.push(res);
}
int res2=numStack.pop();
System.out.println("表达式"+expression+"="+res2);
}
}
package A;
public class ArrayStack {
private int[] stack;
private int maxSize;
private int top=-1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack=new int[this.maxSize];
}
public int peek(){//当前位置的栈顶
return stack[top];
}
public boolean isFull(){
return top==maxSize-1;//按数组0开始,那种思路来考虑的
}
public boolean isEmpty(){
return top==-1;
}
public void push(int value){
if (isFull()){
System.out.println("本栈已满,");
return;
}else {
top++;
stack[top]=value;
}
}
public int pop(){
if (isEmpty()){
System.out.println("本栈已为空,");
return 0;
}else {
int value=stack[top];
top--;
System.out.println("此次出栈的数为:"+value);
//注意,例如‘*’的ASCII=42,所以它就出了42
return value;
}
}
public int priority(int oper){
if (oper==‘*‘||oper==‘/‘){
return 1;
}else if (oper==‘+‘||oper==‘-‘){
return 0;
}else {
return -1;
}
}
public boolean isOper(char val){
return val==‘+‘||val==‘-‘||val==‘*‘||val==‘/‘;
}
public int cal(int num1,int num2,int oper){
int res=0;
switch (oper){
case ‘+‘:
res=num1+num2;
break;
case ‘-‘:
//由主函数中的while得知,num2是栈底,比如3-2中,3就是num2
res=num2-num1;
break;
case ‘*‘:
res=num1*num2;
break;
case ‘/‘:
res=num2/num1;
break;
default:
break;
}
return res;
}
}
用栈来实现计算器