java中缀转后缀_java简单实现中缀转后缀

缺点:目前只实现10以内的四则运算

学到的知识点:

StringBuffer如果想转char数组,首先转String,然后装Char

String tem1=st.toString();

char tem[]=tem1.toCharArray();

如何将字符转数字Float要使用包装类型

Float.valueOf(tem[i]-'0')

import java.nio.CharBuffer;

import java.util.Stack;

public class ZhongZhui {

static Stack stack = new Stack();

public static void main(String[] args) {

String s="5+2*(3*(2-1))";

StringBuilder out1=getLast(s);

float result= calsum(out1);

System.out.println(result);

}

public static float getSum(char op,float n1,float n2){

if(op=='+')

return n1+n2;

if(op=='-')

return n2-n1;

if(op=='*')

return n1*n2;

if(op=='/')

return n2/n1;

return 0;

}

public static float calsum(StringBuilder st){

Stack sum = new Stack();

String tem1=st.toString();

char tem[]=tem1.toCharArray();

for(int i=0;i

if(tem[i]>='0'&&tem[i]<='9'){

System.out.println("temp"+tem[i]);

sum.push(Float.valueOf(tem[i]-'0'));

}else {

float t=getSum(tem[i],sum.pop(),sum.pop());

System.out.println("t"+t);

sum.push(t);

}

}

return sum.pop();

}

public static StringBuilder getLast(String s){

char st[]=s.toCharArray();

StringBuilder out =new StringBuilder();

for(int i=0;i

char temp =st[i];

if(temp==' ')

continue;

//如果是数字,添加到输出字符串

if(temp>='0'&&temp<='9'){

System.out.println("hell0");

out.append(temp);

continue;

}

//如果碰到的是左括号,压入栈中

if(temp=='('){

stack.push(temp);

System.out.println("hello(");

continue;

}

//如果符号是+或者-,当符号栈非空并且栈定元素不为(,

//则将栈顶符号出栈,重复上述步骤,直到while循环不成立,退出,然后把符号压入

//理解也很简单,因为+-的优先级最低,所以符号栈的符号只要不遇到

//左括号就出栈

if(temp=='+'||temp=='-'){

while((!stack.empty())&&(stack.peek()!='(')){

System.out.println("jia");

out.append(stack.pop());

}

stack.push(temp);

continue;

}

//如何遇到右括号,将左括号之后的元素都出栈输出,将左括号出栈不输出

if(temp==')'){

while((!stack.empty())&&(stack.peek()!='(')){

System.out.println("you");

out.append(stack.pop());

}

stack.pop();

continue;

}

//如遇到* /将符号栈的* /出栈并输出

if(temp=='*'||temp=='/'){

while ((!stack.empty())&&(stack.peek()=='*'||stack.peek()=='/')){

System.out.println("cheng");

out.append(stack.pop());

}

stack.push(temp);

continue;

}

}

//字符串遍历完,再检查符号栈,将其中的都输出

while (!(stack.empty())) {

System.out.println("last");

out.append(stack.pop());

}

return out;

}

}

表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页