java堆栈获取后缀表达式(二)

2014-11-24 10:46:15 · 作者: · 浏览: 1
[top]))
{
result+=code[top]+",";
top--;
}
top--; //去掉左括号的栈顶值
System.out.println("栈值:"+code[top]);
System.out.println("右括号打印结果:"+result);
}
else
{
//时数值的话就直接保存到字符串中
result+=str.get(i)+",";
System.out.println("数字");
}
//System.out.println(result);
}
//字符串循环遍历结束后,如果堆栈的值不为空则输出结果
System.out.println(top);
while(top>=1) //栈值是从1开始的 所以遍历是到一就可以结束了
{
System.out.println("最后循环的结果:"+code[top]);
result+=code[top]+",";
top--;
}

System.out.println("操作最后结果:"+result);
return result;
}
else
{
return "";
}
}


/**
* @param text
* @return 参数为文本框的string
* 调用getHuZhui()方法获取到后缀表达式,最后再计算结果
*/
public String countString(String text)
{
String resultString=getHuZhui(text);
top=0;
String[] result=resultString.split(",");
System.out.println("结果字符串数组长度:"+result.length);
for(int i=0;i {
System.out.println("----"+result[i]);
if(isNum(result[i]))
{
code[++top]=result[i]; //如果是数字就入栈
}
else if("+".equals(result[i])) //加号处理
{
code[top-1]=String.valueOf(Double.valueOf(code[top-1])+Double.valueOf(code[top])); //取出栈的第一个和第二个相加再赋给第二个
top=top-1;
System.out.println(code[top]);
}
else if("-".equals(result[i])) //减号处理
{
code[top-1]=String.valueOf(Double.valueOf(code[top-1])-Double.valueOf(code[top]));
top=top-1;
System.out.println(code[top]);
}
else if("*".equals(result[i])) //减号处理
{
code[top-1]=String.valueOf(Double.valueOf(code[top-1])*Double.valueOf(code[top]));
top=top-1;
System.out.println(code[top]);
}
else if("/".equals(result[i])) //减号处理
{
code[top-1]=String.valueOf(Double.valueOf(code[top-1])/Double.valueOf(code[top]));
top=top-1;
System.out.println(code[top]);
}

}
System.out.println("运算结果:"+code[top]);
return code[top];
}

/**
* @param text
* @return 获取第一步需要操作的数组
* 比如(1.2+3)*5-4 转化为集合后为 (,1.2,+,3,),*,5,-,4
* 主要还是将有小数点的数字保存在一个整体里面
*/
public ArrayList getArray(String text)
{
String demo="";
System.out.println("数字函数:"+text);
ArrayList list=new ArrayList();
for(int i=0;i {
String s=text.substring(i,i+1);
System.out.println("截取:"+s);
//System.out.println(s+" ");
if(isNum(s))
{
demo+=s; //如果时数字就加到临时变量中
}
else if(