當前位置:首頁 » 編程語言 » java後綴表達式

java後綴表達式

發布時間: 2022-09-10 20:48:37

1. java 中字元串能不能直接轉換為數學表達式進行計算,不可以要怎麼轉換,求具體代碼。簡單點,最好帶括弧

可是可以,但是特別麻煩.

先要把中綴表達式,轉換為後綴表達式,再計算後綴表達式.

通常把我們日常中看到的數學表達式稱為中綴表達式如:(3+4)*5,
後綴表達式為計算機中容易計算的一種表達式.

A*B+C;轉換為後綴表達式後為:AB*C+;
(A+B)*(C-D);轉換為後綴表達式後為:AB+CD-*;
後綴表達式中沒有括弧,優先順序為從左至右

後綴表達式較中綴表達式而言容易計算.
在中綴表達式中做一項運算要考慮優先順序,所以要檢查後面的字元
在後綴表達式中只要碰到運算符就可以運算了,直到表達式結束.

把中綴表達式轉換為後綴表達式,再計算後綴表達式,這個兩個過程都可以用數據結構(棧)來完成.

下面是一個C語言的例子.你看了應該會明白一點.(和JAVA差不多)
這是2008上半年程序員考試的題目,五個空分別為:
(1)prt++
(2)0
(3)*ptr-'0'
(4)&s,tnum
(5)*result

http://thea.cn/cs/learning/2008-5-26/84218-5.htm

不知道樓主為什麼問這個問題,不可以用其它方式解決嗎?

2. 轉換為前綴及後綴表達式並求值(java實現

它們都是對表達式的記法,因此也被稱為前綴記法、中綴記法和後綴記法。它們之間的區別在於運算符相對與操作數的位置不同:前綴表達式的運算符位於與其相關的操作數之前;中綴和後綴同理。

3. java做一個中綴表達式變後綴表達式的函數的問題

我有個計算器程序,是先把中綴轉後綴的。
------------------
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

class Stack_Float
{
float nums[];
int top;

Stack_Float()
{
nums = new float[50];
top = -1;
}

boolean IsEmpty()
{
if (top == -1)
return true;
else
return false;
}

float Pop_Stack()
{
if (top == -1)
{
return 0;
}
top--;
return nums[top + 1];
}

float GetTop()
{
return nums[top];
}

void Push_Stack(float num)
{
if (top == 49)
return;
top++;
nums[top] = num;
}
}

class Stack_Char
{
char str[];
int top;

Stack_Char()
{
str = new char[50];
top = -1;
}

boolean CanPush(char c)
{
int temp = top;
if (c == '(')
{
while (temp != -1)
{
if (str[temp] == '(')
{
return false;
}
temp--;
}
}
temp = top;
if (c == '[')
{
while (temp != -1)
{
if (str[temp] == '[' || str[temp] == '(')
{
return false;
}
temp--;
}
}
if (c == '{')
{
while (temp != -1)
{
if (str[temp] == '{' || str[temp] == '[' || str[temp] == '(')
{
return false;
}
temp--;
}
}
return true;
}

boolean IsEmpty()
{
if (top == -1)
return true;
else
return false;
}

void Push_Stack(char ch)
{
if (top == 49)
return;
top++;
str[top] = ch;
}

char Pop_Stack()
{
if (top == -1)
return '\0';
top--;
return str[top + 1];
}

char GetTop()
{
if (top == -1)
{
System.out.print("error");
System.exit(0);
}
return str[top];
}
}

public class jisuanqi extends javax.swing.JFrame implements ActionListener
{
JTextField text = new JTextField();
JTextField text1 = new JTextField();
JButton jButton1 = new JButton();
JButton jButton2 = new JButton();
JButton jButton3 = new JButton();
JButton jButton4 = new JButton();
JButton jButton5 = new JButton();
JButton jButton6 = new JButton();
JButton jButton7 = new JButton();
JButton jButton8 = new JButton();
JButton jButton9 = new JButton();
JButton jButton10 = new JButton();
JButton jButton11 = new JButton();
JButton jButton12 = new JButton();
JButton jButton13 = new JButton();
JButton jButton14 = new JButton();
JButton jButton15 = new JButton();
JButton jButton16 = new JButton();
JButton jButton17 = new JButton();
JButton jButton18 = new JButton();
JButton jButton19 = new JButton();
JButton jButton20 = new JButton();
JButton jButton21 = new JButton();
JButton jButton22 = new JButton();
String show = "";

public jisuanqi()
{
initComponents();
}

char[] TranSmit(char str[])
{
char houzhui[] = new char[50]; // 存放後綴表達式的字元串
int i = 0, j = 0;
char c = str[i];
Stack_Char s = new Stack_Char(); // 存放運算符的棧
while (c != '=') // 對算術表達式掃描未結束時
{
if (c >= '0' && c <= '9')
{
while (c >= '0' && c <= '9')// 數字直接入棧
{
houzhui[j] = c;
j++;
i++;
c = str[i];
}
houzhui[j] = '#';// 用#隔開數字
j++;
}
switch (c) // 掃描到運算符時
{
case '+':
case '-':
case '*':
case '/':
case '(':
case '[':
case '{':
if (s.IsEmpty() == true) // 棧空,直接入棧
{
s.Push_Stack(c);
i++;
c = str[i];
break;
}
if (ComPare(s.GetTop(), c) == -1) {
s.Push_Stack(c); // 入棧
i++;
c = str[i];
break;
}
if (ComPare(s.GetTop(), c) == 1) {
houzhui[j] = s.Pop_Stack();// 出棧元素存入後綴表達式
j++;
break;
}

case ')': // 掃描到 )
while (s.GetTop() != '(') // 未掃描到 ( 時,出棧
{
houzhui[j] = s.Pop_Stack();
j++;
}
s.Pop_Stack(); // '(' 出棧
i++;
c = str[i];
break;
case ']': // 掃描到 ]
while (s.GetTop() != '[') // 未掃描到 [ 時,出棧
{
houzhui[j] = s.Pop_Stack();
j++;
}
s.Pop_Stack(); // '[' 出棧
i++;
c = str[i];
break;
case '}': // 掃描到 }
while (s.GetTop() != '{') // 未掃描到 { 時,出棧
{
houzhui[j] = s.Pop_Stack();
j++;
}
s.Pop_Stack(); // '{' 出棧
i++;
c = str[i];
break;
}
}
while (s.IsEmpty() != true)// 把剩餘的運算符直接出棧
{
houzhui[j] = s.Pop_Stack();
j++;
}
houzhui[j] = '=';// 後綴表達式後面加 =
j++;
houzhui[j] = '\0';
j++;
return houzhui;
}

float Count(char str[])
{
Stack_Float s = new Stack_Float();// 定義存放數字的棧
char c = str[0];
int i = 0;
float result = 0, temp, left, right;
while (c != '=') // 未掃描到 = 時
{
if (c >= '0' && c <= '9')// 掃描到數字
{
temp = 0;
while (c != '#')// 未讀到分隔符時
{
temp = temp * 10 + c - '0';
i++;
c = str[i];
}
s.Push_Stack(temp);// 進棧
}
switch (c)// 掃描到運算符時
{
case '+':
{
result = s.Pop_Stack() + s.Pop_Stack();// 2個數字出棧相加
s.Push_Stack(result);// 最後得數進棧
break;
}
case '-':
{
right = s.Pop_Stack();// 右操作數出棧
left = s.Pop_Stack();// 左操作數出棧
result = left - right;
s.Push_Stack(result);
break;
}
case '*':
{
result = s.Pop_Stack() * s.Pop_Stack();// 2個數字出棧相乘
s.Push_Stack(result);
break;
}
case '/':
{
right = s.Pop_Stack();// 右操作數出棧
left = s.Pop_Stack();// 左操作數出棧
result = left / right;
s.Push_Stack(result);
break;
}
}
i++;
c = str[i];
}
return result;
}

int ComPare(char a, char b) // 判斷運算符的優先順序函數
{
int s[][] = {// 棧頂元素高於算術表達式中的元素時, 返回 1,否則返回 -1
{ 1, 1, -1, -1, -1, 1, -1, 1, -1, 1 },
{ 1, 1, -1, -1, -1, 1, -1, 1, -1, 1 },
{ 1, 1, 1, 1, -1, 1, -1, 1, -1, 1 },
{ 1, 1, 1, 1, -1, 1, -1, 1, -1, 1 },
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
{ 1, 1, 1, 1, -1, 1, -1, -1, -1, -1 },
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
{ 1, 1, 1, 1, -1, -1, -1, -1, -1, 1 },
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
{ 1, 1, 1, 1, -1, -1, -1, -1, -1, -1 } };

char x1[] = { '+', '-', '*', '/', '(', ')', '[', ']', '{', '}' };// 棧頂元素
char x2[] = { '+', '-', '*', '/', '(', ')', '[', ']', '{', '}' };// 算術表達式中的元素
int k = 0, m, n = 0;
for (m = 0; m < 10; m++) // 查找2個進行比較的運算符在表中的位置,並返回比較結果
{
for (n = 0; n < 10; n++)
{
if (x1[m] == a && x2[n] == b)
{
k = 1;
break; // 找到比較結果後,跳出循環
}
}
if (k == 1)
break;
}
return s[m][n];// 返回比較結果
}

public void actionPerformed(ActionEvent e)
{
if (e.getSource() == jButton1)
{
show += "1";
text.setText(show);
}
if (e.getSource() == jButton2)
{
show += "2";
text.setText(show);
}
if (e.getSource() == jButton3)
{
show += "3";
text.setText(show);
}
if (e.getSource() == jButton4)
{
show += "4";
text.setText(show);
}
if (e.getSource() == jButton5)
{
show += "5";
text.setText(show);
}
if (e.getSource() == jButton6)
{
show += "6";
text.setText(show);
}
if (e.getSource() == jButton7)
{
show += "7";
text.setText(show);
}
if (e.getSource() == jButton8)
{
show += "8";
text.setText(show);
}
if (e.getSource() == jButton9)
{
show += "9";
text.setText(show);
}
if (e.getSource() == jButton10)
{
show += "0";
text.setText(show);
}
if (e.getSource() == jButton11)
{
show += "+";
text.setText(show);
}
if (e.getSource() == jButton12)
{
show += "-";
text.setText(show);
}
if (e.getSource() == jButton13)
{
show += "*";
text.setText(show);
}
if (e.getSource() == jButton14)
{
show += "/";
text.setText(show);
}
if (e.getSource() == jButton15)
{
show += "(";
text.setText(show);
}
if (e.getSource() == jButton16)
{
show += ")";
text.setText(show);
}
if (e.getSource() == jButton17)
{
show += "[";
text.setText(show);
}
if (e.getSource() == jButton18)
{
show += "]";
text.setText(show);
}
if (e.getSource() == jButton19)
{
show += "{";
text.setText(show);
}
if (e.getSource() == jButton20)
{
show += "}";
text.setText(show);
}
if (e.getSource() == jButton21)
{
show = "";
text.setText("");
text1.setText("");
}
if (e.getSource() == jButton22)
{
show += "=";
text.setText(show);

char str1[] = new char[50];
char str2[] = new char[50];
float result = 0;

str1 = show.toCharArray();
str2 = TranSmit(str1);
result = Count(str2);

text1.setText((new String(str2)).trim());
text.setText("" + result);
show = "";
}
}

private void initComponents()
{
text.setBounds(10, 10, 270, 30);
text1.setBounds(10, 50, 270, 30);
jButton1.setBounds(10, 90, 60, 25);
jButton2.setBounds(80, 90, 60, 25);
jButton3.setBounds(150, 90, 60, 25);
jButton4.setBounds(220, 90, 60, 25);
jButton5.setBounds(10, 120, 60, 25);
jButton6.setBounds(80, 120, 60, 25);
jButton7.setBounds(150, 120, 60, 25);
jButton8.setBounds(220, 120, 60, 25);
jButton9.setBounds(10, 150, 60, 25);
jButton10.setBounds(80, 150, 60, 25);
jButton11.setBounds(150, 150, 60, 25);
jButton12.setBounds(220, 150, 60, 25);
jButton13.setBounds(10, 180, 60, 25);
jButton14.setBounds(80, 180, 60, 25);
jButton15.setBounds(150, 180, 60, 25);
jButton16.setBounds(220, 180, 60, 25);
jButton17.setBounds(150, 210, 60, 25);
jButton18.setBounds(220, 210, 60, 25);
jButton19.setBounds(10, 210, 60, 25);
jButton20.setBounds(80, 210, 60, 25);
jButton21.setBounds(10, 240, 60, 25);
jButton22.setBounds(80, 240, 60, 25);

jButton1.setText("1");
jButton2.setText("2");
jButton3.setText("3");
jButton4.setText("4");
jButton5.setText("5");
jButton6.setText("6");
jButton7.setText("7");
jButton8.setText("8");
jButton9.setText("9");
jButton10.setText("0");
jButton11.setText("+");
jButton12.setText("-");
jButton13.setText("*");
jButton14.setText("/");
jButton15.setText("(");
jButton16.setText(")");
jButton17.setText("[");
jButton18.setText("]");
jButton19.setText("{");
jButton20.setText("}");
jButton21.setText("CE");
jButton22.setText("=");

jButton1.addActionListener(this);
jButton2.addActionListener(this);
jButton3.addActionListener(this);
jButton4.addActionListener(this);
jButton5.addActionListener(this);
jButton6.addActionListener(this);
jButton7.addActionListener(this);
jButton8.addActionListener(this);
jButton9.addActionListener(this);
jButton10.addActionListener(this);
jButton11.addActionListener(this);
jButton12.addActionListener(this);
jButton13.addActionListener(this);
jButton14.addActionListener(this);
jButton15.addActionListener(this);
jButton16.addActionListener(this);
jButton17.addActionListener(this);
jButton18.addActionListener(this);
jButton19.addActionListener(this);
jButton20.addActionListener(this);
jButton21.addActionListener(this);
jButton22.addActionListener(this);

add(text);
add(text1);
add(jButton1);
add(jButton2);
add(jButton3);
add(jButton4);
add(jButton5);
add(jButton6);
add(jButton7);
add(jButton8);
add(jButton9);
add(jButton10);
add(jButton11);
add(jButton12);
add(jButton13);
add(jButton14);
add(jButton15);
add(jButton16);
add(jButton17);
add(jButton18);
add(jButton19);
add(jButton20);
add(jButton21);
add(jButton22);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setBounds(300, 300, 300, 300);
setVisible(true);
}

public static void main(String args[])
{
new jisuanqi();
}
}

4. java後綴表達式實現表達式求值

import java.util.Scanner;
import java.util.Stack;

public class 表達式計算 {
private static Stack<String> num = new Stack<String>();//存後綴表達式
private static Stack<String> sign = new Stack<String>();//存入符號
private static Stack<Integer> result = new Stack<Integer>();//放結果

public static void getGroup(String line){//講字元串轉換為後綴表達式
for(int i=0; i<line.length(); i++){
char c = line.charAt(i);
if((int)c>=48 && (int)c<=57){//當遇到數字的時候,判斷是不是多位數,然後在push進num
int j = i+1;
while(j<line.length() && (line.charAt(j)>=48 && line.charAt(j)<=57)){
j++;
}
num.push(line.substring(i, j));
i = j-1;
}else if(c == '('){//遇到左括弧直接存進num
sign.push(String.valueOf(c));
}else if(c == ')'){//遇到右括弧從sign中pop棧頂元素push到num知道遇到'(',然後再pop掉'('
while(!sign.peek().equals("(")){
num.push(sign.pop());
}
sign.pop();
}else{
int n = 0;
if(!sign.empty()){//如果sign中沒有元素,直接令n = 0
n = getNum(sign.peek().charAt(0));
}
int m = getNum(c);
if(m >= n){//如果當前元素的運算級別比棧頂元素運算級別要高,就直接push進sign
sign.push(String.valueOf(c));
}else{
while(m < n){//如果當前運算運算級別比sign棧頂元素運算級別要低,就將sign棧頂元素pop並且push進num,知道不符合條件
num.push(sign.pop());//輸入例子2*3+6/3的時候,這里一直報錯
if(!sign.empty()){
n = getNum(sign.peek().charAt(0));
}else{
n = 0;
}
}
sign.push(String.valueOf(c));
}
}
}
while(!sign.empty()){
num.push(sign.pop());
}
}

private static int getNum(char c){
int n = 0;
switch(c){
case '+':
case '-':
n = 1;
break;
case '*':
case '/':
n = 2;
break;
}
return n;
}

5. Java 字元串算術表達式求值

import java.util.ArrayList;
import java.util.Stack;

/**itjob
*
* @author yhh
*
*/
public class Calculate {

/**
* 將字元串轉化成List
* @param str
* @return
*/
public ArrayList<String> getStringList(String str){
ArrayList<String> result = new ArrayList<String>();
String num = "";
for (int i = 0; i < str.length(); i++) {
if(Character.isDigit(str.charAt(i))){
num = num + str.charAt(i);
}else{
if(num != ""){
result.add(num);
}
result.add(str.charAt(i) + "");
num = "";
}
}
if(num != ""){
result.add(num);
}
return result;
}

/**
* 將中綴表達式轉化為後綴表達式
* @param inOrderList
* @return
*/
public ArrayList<String> getPostOrder(ArrayList<String> inOrderList){

ArrayList<String> result = new ArrayList<String>();
Stack<String> stack = new Stack<String>();
for (int i = 0; i < inOrderList.size(); i++) {
if(Character.isDigit(inOrderList.get(i).charAt(0))){
result.add(inOrderList.get(i));
}else{
switch (inOrderList.get(i).charAt(0)) {
case '(':
stack.push(inOrderList.get(i));
break;
case ')':
while (!stack.peek().equals("(")) {
result.add(stack.pop());
}
stack.pop();
break;
default:
while (!stack.isEmpty() && compare(stack.peek(), inOrderList.get(i))){
result.add(stack.pop());
}
stack.push(inOrderList.get(i));
break;
}
}
}
while(!stack.isEmpty()){
result.add(stack.pop());
}
return result;
}

/**
* 計算後綴表達式
* @param postOrder
* @return
*/
public Integer calculate(ArrayList<String> postOrder){
Stack stack = new Stack();
for (int i = 0; i < postOrder.size(); i++) {
if(Character.isDigit(postOrder.get(i).charAt(0))){
stack.push(Integer.parseInt(postOrder.get(i)));
}else{
Integer back = (Integer)stack.pop();
Integer front = (Integer)stack.pop();
Integer res = 0;
switch (postOrder.get(i).charAt(0)) {
case '+':
res = front + back;
break;
case '-':
res = front - back;
break;
case '*':
res = front * back;
break;
case '/':
res = front / back;
break;
}
stack.push(res);
}
}
return (Integer)stack.pop();
}

/**
* 比較運算符等級
* @param peek
* @param cur
* @return
*/
public static boolean compare(String peek, String cur){
if("*".equals(peek) && ("/".equals(cur) || "*".equals(cur) ||"+".equals(cur) ||"-".equals(cur))){
return true;
}else if("/".equals(peek) && ("/".equals(cur) || "*".equals(cur) ||"+".equals(cur) ||"-".equals(cur))){
return true;
}else if("+".equals(peek) && ("+".equals(cur) || "-".equals(cur))){
return true;
}else if("-".equals(peek) && ("+".equals(cur) || "-".equals(cur))){
return true;
}
return false;
}

public static void main(String[] args) {
Calculate calculate = new Calculate();
String s = "12+(23*3-56+7)*(2+90)/2";
ArrayList result = calculate.getStringList(s); //String轉換為List
result = calculate.getPostOrder(result); //中綴變後綴
int i = calculate.calculate(result); //計算
System.out.println(i);

}

}

6. java如何求出字元串表達式的結果如「23+4*5-56/4+(2*5+4)」

你可以自己寫個演算法去解析字元串中的加減乘除括弧等特殊字元,然後在計算。或者你寫個存儲過程,通過資料庫的計算機制來計算。

7. java堆棧和後綴表達式求值。

import org.python.util.PythonInterpreter;
public class FirstJavaScript {
public static void main(String args[]) {

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
interpreter.exec("print days[1];");

}// main
}

8. 在JAVA中表達式+xx+x++是怎麼運算的假如x=123按上述運算結果是

+xx+x++
是不是寫錯了
應該是++x+x++吧
當x=123的時候,結果是248
++x和x++的區別在於整體表達式的值
++x表達式的值是 x+1的結果,此時x值也是x+1
x++表達式的值是 x的值 此時x值也是x+1
由此可見 無論前加還是後加,表達式運行完成之後,x的值都進行加1操作
而整體表達式的值不一樣

9. java中綴表達式轉後綴表達式為何會提示下標越界

360問答
高分求解Java問提,用堆棧實現中綴表達式轉後綴表達式?

su694054502 LV12
2013-04-01
要源程序~~
滿意答案

cb123
LV12
2013-04-02
public class s { public static void main(String[] args) { midfix(); } static boolean push(char c) { if(stackLength<50) { myStack[stackLength++]=c; return !STACK_FULL; } else return STACK_FULL; } static char pop() { if(!isEmpty()) { return myStack[--stackLength]; } else return STACK_EMPTY; } static boolean isFull() { if (stackLength==50) return true; else return false; } static boolean isEmpty() { if (stackLength==0) return true; else return false; } static int length() { return stackLength; } static char topValue() { if(!isEmpty()) return myStack[stackLength-1]; else return STACK_EMPTY; }

熱點內容
自動編譯div 發布:2025-01-12 18:51:06 瀏覽:660
手機路由器如何登陸密碼 發布:2025-01-12 18:35:41 瀏覽:464
電光貓無法連接伺服器是什麼原因 發布:2025-01-12 18:32:58 瀏覽:512
迷你世界測試服的密碼從哪裡打開 發布:2025-01-12 18:25:32 瀏覽:111
我的世界手游tis伺服器 發布:2025-01-12 18:24:28 瀏覽:585
青海省分布式伺服器雲主機 發布:2025-01-12 18:12:03 瀏覽:477
英雄聯盟安卓手機版怎麼切換 發布:2025-01-12 18:10:53 瀏覽:382
q5尊享時尚型哪些配置 發布:2025-01-12 18:05:41 瀏覽:230
安卓版本哪裡下載 發布:2025-01-12 18:05:39 瀏覽:557
mc伺服器搭建搜不到 發布:2025-01-12 17:57:37 瀏覽:19