package com.java.demo; import java.util.*; /** * * 基于Java测试【字符窜计算】先乘除后加减 * * @author Administrator * * @description - Stack有时也可以称为“后入先出”(LIFO)集合。 换言之,我们在堆栈里最后“压入”的东西将是以后第一个“弹出”的。 和其他所有Java集合一样,我们压入和弹出的都是“对象”, 所以必须对自己弹出的东西进行“造型”。 本文来自编程入门网:http://www.bianceng.cn/Programming/Java/200705/1569.htm */ public class CountExpression { static String[] operater = new String[20]; static String[] number = new String[20]; public int countExpression(String str) { Stack countStack1 = new Stack(); Stack countStack2 = new Stack(); int result = 0; //在字符串中,必须确认只能包含字符 【+-*/%】,并且要确保非空字符存在 number = str.split("///|//*|//+|//-"); operater = str.split("//d+"); for (int i = 0; i < number.length; i++) { countStack1.push(number[i]); //stack 属于属于后进先出的状态, 将指定的字符添加到stack中 if (i != number.length - 1) { countStack1.push(operater[i + 1]); } } // IsEmpty 【是否有这个变量】 // IsNull 【已有这个变量,但变量的值为空,即变量里没有值】 // "" 【有变量,变量里有值,但值为空字符串,即"" 】 while (!countStack1.isEmpty()) countStack2.push(countStack1.pop()); String op; while (!countStack2.isEmpty()){ result = 0; op = countStack2.pop().toString(); if (op.equals("*")) { result = Integer.parseInt(countStack1.pop().toString()) * Integer.parseInt(countStack2.pop().toString()); countStack1.push(result); continue; } if (op.equals("/")) { result = Integer.parseInt(countStack1.pop().toString()) / Integer.parseInt(countStack2.pop().toString()); countStack1.push(result); continue; } countStack1.push(op); } while (!countStack1.isEmpty()) countStack2.push(countStack1.pop()); while (!countStack2.isEmpty()) { result = 0; op = countStack2.pop().toString(); if (op.equals("+")) { result = Integer.parseInt(countStack1.pop().toString()) + Integer.parseInt(countStack2.pop().toString()); countStack1.push(result); continue; } if (op.equals("-")) { result = Integer.parseInt(countStack1.pop().toString()) - Integer.parseInt(countStack2.pop().toString()); countStack1.push(result); continue; } countStack1.push(op); } return result; // System.out.println(result); } public static void main(String[] args) { int num; CountExpression ct = new CountExpression(); num = ct.countExpression("2+1*2"); System.out.println(num); } }