最近在学习Android平台。 我的目标不仅要学习Android安全,开发也要学。没开发能力怎能称为猿?因为学过中缀后缀表达式相关的算法,以前用C写过,所以实现起来并不是很困难。
表达式求值类:
[Java] 纯文本查看 复制代码
package cn.calc;
public class Expression {
char opTable[] = { '+', '-', '*', '/', '(' };
int leave[] = { 1, 1, 2, 2, 0 };
public String postfix(String exp) {
String hexp = "";
EasyTextStack stack = new EasyTextStack();
for (int i = 0; i < exp.length(); i++) {
char sub;
sub = exp.charAt(i);
if (Character.isDigit(sub)) {
hexp = hexp + sub;
continue;
}
if (sub == '(') {
stack.push("(");
continue;
}
if (sub == ')') {
while (stack.getTop().equals("(") == false) {
hexp = hexp + " " + stack.pop();
}
stack.pop();
continue;
}
if (isOp(sub)) {
if (stack.isEmpty() == false) {
while (getLeave(sub) <= getLeave(stack.getTop().charAt(0))) {
hexp = hexp + " " + stack.pop();
if (stack.isEmpty())
break;
}
}
hexp = hexp + " ";
stack.push(Character.toString(sub));
}
}
while (stack.isEmpty() == false) {
hexp = hexp + " " + stack.pop();
}
return hexp;
}
public int postfix_value(String exp) {
String strGroup[];
int result=0;
EasyTextStack stack = new EasyTextStack();
strGroup = exp.split(" ");
if(strGroup.length==0)
{
return 0;
}
for (int i = 0; i < strGroup.length; i++) {
String string = strGroup[i];
if(isOp(string.charAt(0)))
{
int v1,v2;
if(stack.getCount()<2)
return 0;
v1= Integer.parseInt(stack.pop());
v2 = Integer.parseInt(stack.pop());
if(string.equals("-"))
{
result = v2-v1;
stack.push(String.format("%d",result));
continue;
}
if(string.equals("+"))
{
result=v1+v2;
stack.push(String.format("%d",result));
continue;
}
if(string.equals("*"))
{
result = v1*v2;
stack.push(String.format("%d", result));
continue;
}
if(string.equals("/"))
{
result = v2/v1;
stack.push(String.format("%d", result));
continue;
}
}else
{
stack.push(string); // 数字入栈
}
}
if(stack.getCount()==1)
return Integer.parseInt(stack.pop());
return 0;
}
private boolean isOp(char op) {
for (int i = 0; i < opTable.length; i++)
if (opTable[i] == op)
return true;
return false;
}
private int getLeave(char op) {
for (int i = 0; i < opTable.length; i++)
if (opTable[i] == op)
return leave[i];
return 0;
}
}
论坛怎么不能上传附件?
|