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+0.2*0.5/3");   //2+2*5/3的计算结果是正确的,加入小数点后出现问题 System.out.println(num);
}
}

解决方案 »

  1.   

    精度不对,你num是int的。而小数应该float或者double型的
      

  2.   

    第一个问题:
    你看下正则表达式就行了。
    number = str.split("\\/|\\*|\\+|\\-");
    operater = str.split("\\d+");这个正则表达式分法,只对是没有数字的才有用。当你输入的表达式是:2+2*5/3,用正则表达式split后,得:
    number=[2,2,5,3];
    operater=['',+,*,/,''];
    分解是没问题的。当你输入的表达式是:2+0.2*0.5/3,用正则表达式split后,得:
    number=[2,0.2,0.5,3];      //数字是没问题的
    operater=['',+,.,*,.,/,''];    //多了.号
    分解是有问题。第二个问题:
    下面用parseInt()....这个是用来解析整型的,用来解析浮点就不对。
      

  3.   

    谢谢各楼主!
          ouotuo楼主的分析是对的。要点在于存放如堆栈时出现了空字符,分割字符串时将非数值 ‘.’同时也添加上去了。
          问题已经得到解决。再次谢谢各楼主!