您的位置:首页 > 其它

使用后缀表达式计算表达式

2011-12-05 09:38 246 查看
需求:输入字符串表达式,计算表达式结果

解决:将输入的表示转化为后缀表达式形式(也称作逆波兰式),再计算结果。

package com.phh;

import java.util.Stack;

public class CalculatedString {

/**
* 根据中缀表达式计算结果
*
* @param expression
* @return
*/
public Float calculate(String expression) {
Float result = null;

Stack stack = new Stack();

char[] exp = expression.toCharArray();
StringBuffer s = new StringBuffer();
for (char c : exp) {

if (c == 32) {
if (!s.toString().equals("")) {
stack.push(Float.valueOf(s.toString()));
s = new StringBuffer();
}
}

if (c >= 48 && c <= 57) {
s.append(c);
}

if (c == 42 || c == 43 || c == 45 || c == 47) {
if (!s.toString().equals("")) {
stack.push(Float.valueOf(s.toString()));
s = new StringBuffer();
}
}

if (c == 42) {
float b = (Float) stack.pop();
float a = (Float) stack.pop();
stack.push(a * b);
}

if (c == 43) {
float b = (Float) stack.pop();
float a = (Float) stack.pop();
stack.push(a + b);
}

if (c == 45) {
float b = (Float) stack.pop();
float a = (Float) stack.pop();
stack.push(a - b);
}

if (c == 47) {
float b = (Float) stack.pop();
float a = (Float) stack.pop();
stack.push(a / b);
}

}

result = (Float) stack.pop();

return result;
}

public static void main(String[] args) {
MiddleToLast m = new MiddleToLast();
CalculatedString cal = new CalculatedString();
String expression = m.transfer("15+18-2*10+(9-6+2)/2+18");
System.out.println(cal.calculate(expression));
}
}


package com.phh;

import java.util.Stack;

public class MiddleToLast {

/**
* 将输入的中缀表达式转化为后缀表达式
*
* @param 中缀表达式
* @return 后缀表达式
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public String transfer(String middle) {
StringBuffer last = new StringBuffer();

Stack stack = new Stack();

int level = 0;

char middleChar[] = middle.toCharArray();
for (char c : middleChar) {
if (c >= 48 && c <= 57) {
last.append(c);
}
if (c == 40) {
stack.push(c);
}
if (c == 43 || c == 45) {
if (level > 1) {
while (!stack.isEmpty()
&& 40 != (Character) stack.firstElement()) {
char c1 = (Character) stack.pop();
if (c1 != 40) {
last.append(c1);
}
}
}
stack.push(c);
last.append(" ");
level = 1;
}
if (c == 42 || c == 47) {
stack.push(c);
level = 2;
last.append(" ");
}
if (c == 41) {
while (!stack.isEmpty()) {
char c1 = (Character) stack.pop();
if (c1 != 40) {
last.append(c1);
} else {
break;
}
}
}
}

while (!stack.isEmpty()) {
char c1 = (Character) stack.firstElement();
if (c1 != 40) {
last.append(stack.pop());
}
}

return last.toString();
}

public static void main(String[] args) {
MiddleToLast m = new MiddleToLast();
String middle = "9+(3-1)*3+10/2";
System.out.println(m.transfer(middle));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: