当前位置:首页 » 编程语言 » 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; }

热点内容
算法工作原理 发布:2025-01-12 20:36:38 浏览:24
网络访问监控软件 发布:2025-01-12 20:26:57 浏览:465
养羊啦源码 发布:2025-01-12 20:25:48 浏览:570
轩逸朗逸哪个配置最好 发布:2025-01-12 20:10:00 浏览:50
主板存储器分 发布:2025-01-12 20:04:46 浏览:377
数据库逻辑运算 发布:2025-01-12 20:03:54 浏览:571
javawindows服务器搭建 发布:2025-01-12 19:59:37 浏览:571
linux关闭iptables 发布:2025-01-12 19:58:49 浏览:150
服务器电脑名字改了影响数据库吗 发布:2025-01-12 19:58:44 浏览:653
手机存储优化 发布:2025-01-12 19:58:43 浏览:356