表達(dá)式求值 逆波蘭表達(dá)式算法 如下:
為源匯等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及源匯網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站、源匯網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專(zhuān)業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!
import java.util.ArrayList;
import java.util.List;
public class MyStack {
private ListString l;
private int size;
public String top;
public MyStack() {
l = new ArrayListString();
size = 0;
top = null;
}
public int size() {
return size;
}
public void push(String s) {
l.add(s);
top = s;
size++;
}
public String pop() {
String s = l.get(size - 1);
l.remove(size - 1);
size--;
top = size == 0 ? null : l.get(size - 1);
return s;
}
}
import java.util.ArrayList;
import java.util.List;
public class Nbl {
private static MyStack ms1 = new MyStack();//生成逆波蘭表達(dá)式的棧
private static MyStack ms2 = new MyStack();//運(yùn)算棧
/**
* 將字符串轉(zhuǎn)換為中序表達(dá)式
*/
public static ListString zb(String s) {
ListString ls = new ArrayListString();//存儲(chǔ)中序表達(dá)式
int i = 0;
String str;
char c;
do {
if ((c = s.charAt(i)) 48 || (c = s.charAt(i)) 57) {
ls.add("" + c);
i++;
} else {
str = "";
while (i s.length() (c = s.charAt(i)) = 48
(c = s.charAt(i)) = 57) {
str += c;
i++;
}
ls.add(str);
}
} while (i s.length());
return ls;
}
/**
* 將中序表達(dá)式轉(zhuǎn)換為逆波蘭表達(dá)式
*/
public static ListString parse(ListString ls) {
ListString lss = new ArrayListString();
for (String ss : ls) {
if (ss.matches("\d+")) {
lss.add(ss);
} else if (ss.equals("(")) {
ms1.push(ss);
} else if (ss.equals(")")) {
while (!ms1.top.equals("(")) {
lss.add(ms1.pop());
}
ms1.pop();
} else {
while (ms1.size() != 0 getValue(ms1.top) = getValue(ss)) {
lss.add(ms1.pop());
}
ms1.push(ss);
}
}
while (ms1.size() != 0) {
lss.add(ms1.pop());
}
return lss;
}
/**
* 對(duì)逆波蘭表達(dá)式進(jìn)行求值
*/
public static int jisuan(ListString ls) {
for (String s : ls) {
if (s.matches("\d+")) {
ms2.push(s);
} else {
int b = Integer.parseInt(ms2.pop());
int a = Integer.parseInt(ms2.pop());
if (s.equals("+")) {
a = a + b;
} else if (s.equals("-")) {
a = a - b;
} else if (s.equals("*")) {
a = a * b;
} else if (s.equals("\")) {
a = a / b;
}
ms2.push("" + a);
}
}
return Integer.parseInt(ms2.pop());
}
/**
* 獲取運(yùn)算符優(yōu)先級(jí)
* +,-為1 *,/為2 ()為0
*/
public static int getValue(String s) {
if (s.equals("+")) {
return 1;
} else if (s.equals("-")) {
return 1;
} else if (s.equals("*")) {
return 2;
} else if (s.equals("\")) {
return 2;
}
return 0;
}
public static void main(String[] args) {
System.out.println(jisuan(parse(zb("0-8+((1+2)*4)-3+(2*7-2+2)"))));
}
}
import java.util.Stack;
/**
* @author wengsh
* @date 2010-6-3 用 輸入 (6+5)*(5+5) 測(cè)試一下
*/
public class MyDemo {
public static void main(String[] a) {
StackCharacter stack = new StackCharacter();
StringBuffer sb = new StringBuffer();
if (a.length 1) {
System.out.println("參數(shù)長(zhǎng)度不夠");
} else {
String s = a[0].trim();
char[] c = s.toCharArray();
try {
for (int i = 0; i c.length; i++) {
int priority = getPriority(c[i]);
if (priority == -1) { // 如果是數(shù)字
sb.append(c[i]); // 輸出數(shù)字或都字母
} else {
if (stack.isEmpty()) {// 當(dāng)棧為空時(shí)
stack.push(c[i]); // 把字符壓入棧
} else {// 當(dāng)棧為不空時(shí)
if (priority == -2) { // 如果是 ')'
while (!stack.isEmpty()
getPriority(stack.peek()) != 8) {
sb.append(stack.pop());// 把'('之上的字符彈出棧并輸出
}
stack.pop(); // 棧彈出'('
} else {
// 當(dāng)要壓入棧的字符的優(yōu)先級(jí)小于 等于棧頂字符的優(yōu)先級(jí)且棧頂字符不為'('時(shí)
while (!stack.isEmpty()
priority = getPriority(stack.peek())
getPriority(stack.peek()) != 8) {
sb.append(stack.pop()); // 彈出棧頂字符并輸出
}
stack.push(c[i]);// 將此時(shí)的字符壓入棧頂
}
}
}
}
// 讀到輸入末尾
while (!stack.isEmpty()) {
sb.append(stack.pop()); // 彈出棧中所有元素并輸出
}
System.out.println(sb); // 結(jié)果 65+55+*
System.out.println(calstack(sb.toString()));//結(jié)果 110.0
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 獲得字符串優(yōu)先級(jí)如果字符不在給定的范圍內(nèi),則拋出異常,數(shù)字和字母的優(yōu)先級(jí)最低
*
* @param c
* @return
* @throws Exception
*/
public static int getPriority(char c) throws Exception {
int priority = -1;
if (Character.isDigit(c)) {
priority = -1;
} else if (Character.isLetter(c)) {
priority = 0;
} else {
if (c == '(') {
priority = 8;
} else if (c == '*' || c == '/') {
priority = 5;
} else if (c == '+' || c == '-') {
priority = 4;
} else if (c == ')') {
priority = -2;
} else {
throw new Exception("無(wú)法解析的前序表達(dá)式: " + c);
}
}
return priority;
}
/**
* 計(jì)算棧結(jié)果
* 6+5*8
* @param s
* @return
*/
public static float calstack(String s) {
StackFloat stack = new StackFloat();
char[] c = s.toCharArray();
try {
for (int i = 0; i c.length; i++) {
int priority = getPriority(c[i]);
if (priority == -1) {
stack.push(new Float(Character.digit(c[i], 10)));
} else {
stack.push(cal(stack.pop(), stack.pop(), c[i]));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stack.pop();
}
/**
* a b 運(yùn)算
* @param a
* @param b
* @param opertor
* @return
*/
public static float cal(float a, float b, char opertor) {
float r = 0;
switch (opertor) {
case '+':
r = a + b;
break;
case '-':
r = a - b;
break;
case '*':
r = a * b;
break;
case '/':
r = a / b;
break;
}
return r;
}
}
while(Character.isDigit(chars[i])||chars[i]=='.') {
s.append(chars[i]);
}
這一段是死循環(huán)。。stack一直追加參數(shù),所以溢出了
下面的代碼是用來(lái)計(jì)算表達(dá)式的,看看是不是你要的
public class OPNode {
char op;// 運(yùn)算符號(hào)
int level;// 優(yōu)先級(jí)
//設(shè)置優(yōu)先級(jí)
public OPNode(String op) {
this.op = op.charAt(0);
if (op.equals("+") || op.equals("-")) {
this.level = 1;
} else if (op.equals("*") || op.equals("/")) {
this.level = 2;
} else if (op.equals("(")) {
this.level = -3;
} else {
this.level = -1;
}
}
}
//主類(lèi)
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OPText {
public static void main(String[] args) {
String expression = "2+2+(8-2)/3";// 要計(jì)算的表達(dá)式
List list = new LinkedList();
//正則式
Pattern entryOfExpression = Pattern
.compile("[0-9]+(\\.[0-9]+)?|\\(|\\)|\\+|-|\\*|/");
Deque stack = new LinkedList();//棧
Matcher m = entryOfExpression.matcher(expression);
while (m.find()) {
//提取語(yǔ)素
String nodeString = expression.substring(m.start(), m.end());
if (nodeString.matches("[0-9].*")) {
list.add(Double.valueOf(nodeString));//如果是數(shù)字直接送入列表
} else {
OPNode opn = new OPNode(nodeString);//如果是運(yùn)算符
int peekLevel = (stack.peek() == null) ? 0 : ((OPNode) stack
.peek()).level;
if (opn.level =peekLevel) {
stack.push(opn);//新的運(yùn)算符比舊的優(yōu)先級(jí)別高則入棧
} else {
if (opn.level == -1) {
OPNode temp = (OPNode) stack.pop();
while (temp.level != -3) {//如果為"("則一直出棧一直到")"
list.add(temp);
System.out.println(nodeString);
temp = (OPNode) stack.pop();
}
} else if (opn.level == -3) {
stack.push(opn);
} else {//如果新運(yùn)算符比棧頂運(yùn)算符底則一直出棧
OPNode temp = (OPNode) stack.pop();
while (temp.level opn.level) {
list.add(temp);
if (stack.isEmpty()) {
break;
}
temp = (OPNode) stack.pop();
}
stack.push(opn);
}
}
}
}
OPNode temp = null;
while (!stack.isEmpty()) {
temp = (OPNode) stack.pop();
list.add(temp);
}//后續(xù)表達(dá)式計(jì)算
stack.clear();
for (Object o : list) {
if (o instanceof Double) {
stack.push(o);//為數(shù)字入棧
} else {
double op2 = ((Double) stack.pop()).doubleValue();
double op1 = ((Double) stack.pop()).doubleValue();
switch (((OPNode) o).op) {
case '+':
stack.push(op1 + op2);
break;
case '-':
stack.push(op1 - op2);
break;
case '*':
stack.push(op1 * op2);
break;
case '/':
stack.push(op1 / op2);
break;
}
}
}
System.out.println("結(jié)果為:" + stack.pop());
}
}
呃,太晚了,沒(méi)心思去改了
明天再說(shuō)
分享文章:逆波蘭java代碼,逆波蘭表達(dá)式j(luò)ava
鏈接分享:http://sd-ha.com/article20/hdhcjo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、移動(dòng)網(wǎng)站建設(shè)、動(dòng)態(tài)網(wǎng)站、品牌網(wǎng)站制作、品牌網(wǎng)站建設(shè)、網(wǎng)站內(nèi)鏈
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
全網(wǎng)營(yíng)銷(xiāo)推廣知識(shí)