如何用递归方法实现postfix计算?

ryantao2010 2012-01-28 06:58:53
譬如说在cmd下输入
java postfixCal 23+4-
会得到1?
...全文
94 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
cstur4 2012-01-28
  • 打赏
  • 举报
回复
用引号可以解决这个问题

java PostFix 2 3 "*"


[Quote=引用 3 楼 qqlwq123 的回复:]

引用 1 楼 cstur4 的回复:

Java code


import java.util.LinkedList;
import java.util.List;


public class PostFix {


public static void main(String[] args) {

StringBuilder sb = new StringBui……
[/Quote]
cstur4 2012-01-28
  • 打赏
  • 举报
回复


import java.util.LinkedList;
import java.util.List;


public class PostFix {


public static void main(String[] args) {

StringBuilder sb = new StringBuilder();
for(int i=0;i<args.length;i++)
sb.append(args[i]+" ");
System.out.println(calPostFix(sb.toString()));

}
private static double calPostFix(String str)
{

List<String> parts = new LinkedList<String>();
for(int i=0;i<str.length();)
{
if(str.charAt(i)==' ')
{
i++;
continue;
}
int pos = i;
while(Character.isDigit(str.charAt(i)) || str.charAt(i)=='.') //数字
i++;
if(pos!=i)
{
parts.add(str.substring(pos, i));
continue;
}
//操作符
parts.add(str.charAt(i++)+"");

}

double nowValue = Double.parseDouble(parts.get(0));
return calPostFixParts(parts, 1, nowValue);


}
/**这里递归调用**/
private static double calPostFixParts(List<String> parts, int pos, double nowValue)
{
if(pos>=parts.size())
return nowValue;

double res = cal(nowValue, parts.get(pos), parts.get(pos+1));
return calPostFixParts(parts, pos+2, res);
}

protected static double cal(double m, String b, String operator)
{
if(operator.length()!=1)
throw new RuntimeException("操作符不合法");

Character op = operator.charAt(0);
double n = Double.valueOf(b);
switch(op)
{
case '+':return m+n;
case '-':return m-n;
case '*':return m*n;
case '/':return m/n;
case '^':return Math.pow(m, n);
default:throw new RuntimeException("操作符不合法");
}
}

}

qqlwq123 2012-01-28
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 cstur4 的回复:]

Java code


import java.util.LinkedList;
import java.util.List;


public class PostFix {


public static void main(String[] args) {

StringBuilder sb = new StringBuilder();
……
[/Quote]
main入口参数'*'是不能使用的,JAVA没法正确获得这个字符的,请用其他字符代替乘号。
cstur4 2012-01-28
  • 打赏
  • 举报
回复
你需要用空格来分隔参数,如:java PostFix 2 3+4-

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧