简单字符串四则运算(Java)

xieqingtao 2010-08-10 02:52:16
package com.feiyang.arithmetic;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StackExpression
{

private String str;

private Stack<String> operators = new Stack<String>();

private Stack<String> numerics = new Stack<String>();

public StackExpression(String str)
{
this.str = str;
}

public float result()
{
Object[] nums = splitStr("[+|\\-|*|/]");
Object[] ops = splitStr("\\d");
String[] dividedStr = new String[nums.length + ops.length];
//compsite the string to an array
for (int i = 0, j = 0; j < nums.length; i++, j++)
{
dividedStr[i] = (String) nums[j];
if (j < ops.length)
{
i = i + 1;
dividedStr[i] = (String) ops[j];
}
}

operators.push(null);

for (int k = 0; k < dividedStr.length;)
{
if (isNumber(dividedStr[k]))
{
numerics.push(dividedStr[k]);
k++;
System.out.println("------number:" + numerics.toString());
}
else
{
String top = operators.peek();
if (null != top
&& isHigh(operators.peek().charAt(0), dividedStr[k].charAt(0)))
{
float f2 = Float.parseFloat(numerics.pop());
float f1 = Float.parseFloat(numerics.pop());
char op = operators.pop().charAt(0);
numerics.push(String.valueOf(calculate(f1, f2, op)));
}
else
{
operators.push(dividedStr[k]);
k++;
}
System.out.println("------op:" + operators.toString());
}
}

while (operators.peek() != null)
{
float f2 = Float.parseFloat(numerics.pop());
float f1 = Float.parseFloat(numerics.pop());
char op = operators.pop().charAt(0);
numerics.push(String.valueOf(calculate(f1, f2, op)));
System.out.println("------number:" + numerics.toString());
System.out.println("------op:" + operators.toString());
}

return Float.parseFloat(numerics.peek());
}

private Object[] splitStr(String pattern)
{
Pattern p = Pattern.compile(pattern);
String[] strsWithEmpty = p.split(this.str);
List<String> list = new ArrayList<String>();

for (int i = 0; i < strsWithEmpty.length; i++)
{
if (strsWithEmpty[i].length() != 0)
{
list.add(strsWithEmpty[i]);
}
}
return list.toArray();
}

boolean isNumber(String num)
{
Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher(num);
return m.matches();
}

boolean isHigh(int first, int second)
{
boolean ret = true;

if ((Operators.MINUS.getOp() == first || Operators.PLUS.getOp() == first)
&& (Operators.MUTIPLY.getOp() == second || Operators.DIV.getOp() == second))
{
ret = false;
}

return ret;

}

float calculate(float a, float b, char op)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return -1;
}

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
String str = "645-90/4+89/25*3-8";
StackExpression c = new StackExpression(str);
System.out.println(str + "=" + c.result());

}

}





package com.feiyang.arithmetic;

import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class PostFixExpression
{

private String str;

PostFixExpression(String str)
{
this.str = str;
}

public float result()
{
Stack<String> numbers = new Stack<String>();
numbers.push(null);

this.str = covertPostEx();
String[] splitStr = this.str.split(" ");

for (int i = 0; i < splitStr.length; i++)
{
if (isNumber(splitStr[i]))
{
numbers.push(splitStr[i]);
}
else
{
float f1 = Float.parseFloat(numbers.pop());
float f2 = Float.parseFloat(numbers.pop());
numbers.push(String.valueOf(calculate(f2, f1, splitStr[i].charAt(0))));
}
}

return Float.parseFloat(numbers.pop());
}

public String covertPostEx()
{
String postEx = "";
Stack<String> ops = new Stack<String>();
ops.push(null);

int i = 0;
while (i < this.str.length())
{
StringBuffer tmp = new StringBuffer();
if (isNumber(String.valueOf(str.charAt(i))))
{
do
{
tmp.append(str.charAt(i));
i++;
}
while (i < this.str.length() && isNumber(String.valueOf(str.charAt(i))));
postEx += tmp.toString();
postEx += " ";
}
else
{
String top = ops.peek();
if (top != null)
{
if (isHigh(top.charAt(0), str.charAt(i)))
{
postEx += ops.pop();
postEx += " ";
}
else
{
ops.push(String.valueOf(str.charAt(i)));
i++;
}
}
else
{
ops.push(String.valueOf(str.charAt(i)));
i++;
}
}

}

while (null != ops.peek())
{
postEx += ops.pop();
postEx += " ";
}

System.out.println(this.str + " postFix=" + postEx);

return postEx;
}

boolean isHigh(int first, int second)
{
boolean ret = true;

if ((Operators.MINUS.getOp() == first || Operators.PLUS.getOp() == first)
&& (Operators.MUTIPLY.getOp() == second || Operators.DIV.getOp() == second))
{
ret = false;
}

return ret;

}

boolean isNumber(String num)
{
Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher(num);
return m.matches();
}

float calculate(float a, float b, char op)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
return -1;
}

/**
* @param args
*/
public static void main(String[] args)
{
String str = "645-90/4+89/25*3-8";
PostFixExpression post = new PostFixExpression(str);
System.out.println(str + "=" + post.result());
}

}









...全文
538 5 打赏 收藏 举报
写回复
5 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
pb_myown 2011-10-21
一个栈不够么?!
  • 打赏
  • 举报
回复
黄海深 2011-10-21
射门,但是还有滴。
  • 打赏
  • 举报
回复
报错了啊 Operators.MINUS.getOp() ???
  • 打赏
  • 举报
回复
toplinq 2010-08-10
楼主在写博客么
  • 打赏
  • 举报
回复
小楫轻舟 2010-08-10
不明白楼主干嘛!
  • 打赏
  • 举报
回复
发帖
数据结构与算法

3.2w+

社区成员

数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
帖子事件
创建了帖子
2010-08-10 02:52
社区公告
暂无公告