/**
* 计算算数表达式的值
* For example:
* ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
* ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
* @author zl
* 思路:
* 这个问题可以通过使用堆栈来解决。
* (1)我们可以循环遍历给定数组中的每个元素。
* (2)当它是一个数字,把它推到堆栈。
* (3) 当它是一个操作符时,从堆栈中弹出两个数字,进行计算,并推回结果。
*
*/
public class EvaluateValueOfArithmeticExpression {
private static void evoe(String[] strArr){
String str = "+-*/";
Stack<String> stack = new Stack<String>();
//2.0遍历数组中的每一个元素
for(String s : strArr){
if(!str.contains(s)){//如果是数字,放入栈中
stack.push(s);
}else{
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
switch(s){
case "+" :
stack.push(String.valueOf(a+b));
break;
case "-" :
stack.push(String.valueOf(b-a));
break ;
case "*" :
stack.push(String.valueOf(a*b));
break;
case "/" :
stack.push(String.valueOf(b/a));
break ;
}
}
}
System.out.println(stack.pop());
}
public static void main(String[] args) {
//1.0创建数组
String [] strArr = { "0", "2", "-", "3", "+" };
evoe(strArr);
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有