用栈计算数学表达式

在这里插入代码片
package hello;

import java.util.*;

public class Ha {	
private static Stack<Character> a=new Stack<Character>();//存操作符
private static Stack<Double> b=new Stack<Double>();//存操作数
public static void main(String []args)
{Scanner input=new Scanner(System.in);
System.out.println("请输入表达式");
String c=input.next();
StringTokenizer d=new StringTokenizer(c,"()+-*/",true);
while(d.hasMoreTokens())
{c=d.nextToken().trim();
if(c.length()==0)
	continue;
else if(c.charAt(0)=='+'||c.charAt(0)=='-')
	{while(!a.empty()&&(a.peek()=='+'||a.peek()=='-'||a.peek()=='*'||a.peek()=='/'))
		suan();
	a.push(c.charAt(0));}
else if(c.charAt(0)=='*'||c.charAt(0)=='/')
{while(!a.empty()&&(a.peek()=='*'||a.peek()=='/'))
	suan();
a.push(c.charAt(0));}
else if(c.charAt(0)=='(')
	a.push('(');
else if(c.charAt(0)==')')
{
	while(a.peek()!='(')
		suan();
	a.pop();}
else 
	b.push(new Double(c));
}
while(!a.empty())
suan();
System.out.println("结果是"+b.pop());
}
public static void suan(){
	double b1=b.pop();
	double b2=b.pop();
	char a1=a.pop();
	if(a1=='+')
		b.push(b1+b2);
	else if(a1=='-')
		b.push(b2-b1);
	else if(a1=='*')
		b.push(b2*b1);
	else if(a1=='/')
		b.push(b2/b1);
}
}

在这里插入图片描述

发布了130 篇原创文章 · 获赞 16 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/feiqipengcheng/article/details/103207111