「java中缀」java中缀表达式转后缀表达式代码
本篇文章给大家谈谈java中缀,以及java中缀表达式转后缀表达式代码对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
- 1、java中缀转后缀
- 2、编写一个能够计算中缀表达式的java程序
- 3、java做一个中缀表达式变后缀表达式的函数的问题
- 4、java里中缀表达式怎么变成后缀表达式 用堆栈 只要说下原理就行了啊 文字表达下 有括号的情况
java中缀转后缀
首先inOrderList的类型是ArrayListString。ArrayListString就是一个可变长数组,数组里的每个元素是一个字符串。
其次,第二个问题问的不是很明确。[所有集合的方法]指的是什么?ArrayList只是一种集合,常用的还有map等。后面的是泛型,jdk1.5以后才支持的,便于类型的指定,在编译的级别可以杜绝一部分类型转换的错误。补充一下,但泛型不能根本上解决集合元素,类型转换的所有问题。
编写一个能够计算中缀表达式的java程序
;
基本上就是先做词法分析(Lexical Analysis),然后再依优先级别把所有操作符和相关的操作数逐一化解成数值,
一直到整个表达式被化解成一个数值(或碰上表达式里的格式或数值范围错误)为止。
代码里,tokenize( ) 负责词法分析,剩下的都交给 evaluate( ) 。
evaluate( ) 能正确地求出空格数量和位置不规则的表达式
(比如 " -8-(+ 6*(1.5+723 )--9)+2^+3 ^- 5.2/16 ")。
注:
我没在 evaluate( ) 里捕捉任何异常,因为从里头冒出的任何异常都表示被传入的参数有错误。
(那意味着 evaluate( ) 的调用应该被放在 try block 里。)
import java.util.*;
class Expression {
public static void main( String[ ] args ) {
String expr = " -8-(+ 6*(1.5+723 )--9)+2^+3 ^- 5.2/16 ";
try {
System.out.println( evaluate( expr ) );
} catch ( Exception e ) {
System.out.println( "Syntax or numeric range error!" );
}
}
public static double evaluate( String expr ) {
ListString tokens = tokenize( expr );
// Recursively eliminate all operators, in descending order of priority,
// till a numeric value is obtained from expr or till error is detected.
// first of all, get rid of all parentheses
int open = tokens.indexOf( "(" ),
close = tokens.lastIndexOf( ")" );
if ( open != -1 ) // parentheses mismatch will be caught by subList( )
return evaluate( join( tokens.subList( 0, open ) ) +
evaluate( join( tokens.subList( open + 1, close ) ) ) +
join( tokens.subList( close + 1, tokens.size( ) ) ) );
// now, get rid of binaries
String[ ][ ] binaries = { { "+", "-" }, // priority-0 is the lowest
{ "*", "/" },
{ "^" } }; // only one R2L (right-to-left)
ListString listOfR2L = Arrays.asList( "^" );
for ( int priority = binaries.length - 1; priority = 0; priority-- ) {
List binariesOfCurrentPriority = Arrays.asList( binaries[ priority ] );
int pos = Algorithms.findFirstOf( binariesOfCurrentPriority, tokens );
if ( listOfR2L.contains( binariesOfCurrentPriority.get( 0 ) ) )
pos = Algorithms.findLastOf( binariesOfCurrentPriority, tokens );
if ( pos != -1 )
return evaluate( join( tokens.subList( 0, pos - 1 ) ) +
operate( tokens.get( pos ),
tokens.get( pos - 1 ),
tokens.get( pos + 1 ) ) +
join( tokens.subList( pos + 2, tokens.size( ) ) ) );
}
// at this point, expr should be a numeric value convertible to double
return Double.parseDouble( tokens.get( 0 ) );
}
public static double operate( String operator, String a, String b ) {
double x = Double.parseDouble( a ), y = Double.parseDouble( b );
if ( operator.equals( "+" ) ) return x + y;
if ( operator.equals( "-" ) ) return x - y;
if ( operator.equals( "*" ) ) return x * y;
if ( operator.equals( "/" ) ) return x / y;
if ( operator.equals( "^" ) ) return Math.pow( x, y );
throw new IllegalArgumentException( "Unknown operator: " + operator );
}
public static boolean isArithmeticOperator( String s ) {
return s.length( ) == 1 "+-*/^".indexOf( s ) != -1;
}
public static ListString tokenize( String expr ) {
// split by (while "capturing" all) operators by positive look around
final String pattern = "(?=[-+*/^()])|(?=[-+*/^()])";
ListString tokens =
new ArrayListString( Arrays.asList( expr.split( pattern ) ) );
// Trim all tokens, discard empty ones, and join sign to number.
for ( int i = 0; i tokens.size( ); i++ ) {
String current = tokens.get( i ).trim( ),
previous = i 0 ? tokens.get( i - 1 ) : "+";
if ( current.length( ) == 0 )
tokens.remove( i-- ); // decrement, or miss the next token
else
if ( isArithmeticOperator( current )
isArithmeticOperator( previous )
i + 1 tokens.size( ) ) {
tokens.set( i + 1, current + tokens.get( i + 1 ).trim( ) );
tokens.remove( i ); // no decrement, to skip the next token
} else
tokens.set( i, current );
}
return tokens;
}
private static String join( ListString strings ) {
return strings.toString( ).replaceAll( "[,\\[\\]]", "" );
}
}
// see C++'s STL algorithm find_first_of( ) and find_last_of( ) for semantics
class Algorithms {
public static int findFirstOf( List what, List in ) {
ListInteger locations = new ArrayListInteger( );
for ( Object o: what )
if ( in.contains( o ) )
locations.add( in.indexOf( o ) );
return locations.isEmpty( ) ? -1 : Collections.min( locations );
}
public static int findLastOf( List what, List in ) {
ListInteger locations = new ArrayListInteger( );
for ( Object o: what )
if ( in.contains( o ) )
locations.add( in.lastIndexOf( o ) );
return locations.isEmpty( ) ? -1 : Collections.max( locations );
}
}
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();
}
}
java里中缀表达式怎么变成后缀表达式 用堆栈 只要说下原理就行了啊 文字表达下 有括号的情况
将中缀表达式转换为后缀表达式的算法思想:
·当读到数字直接送至输出队列中
·当读到运算符t时,
a. 将栈中所有优先级高于或等于t的运算符弹出,送到输出队列;
b. t进栈
·读到左括号时总是将它压入栈中
·读到右括号时,将靠近栈顶的第一个左括号上面的运算符全部依次弹出,送至输出队列后,再丢弃左括号。
运用后缀表达式进行计算的具体做法:
·建立一个栈S
·从左到右读后缀表达式,读到数字就将它转换为数值压入栈S中,读到运算符则从栈中依次弹出两个数分别到Y和X,然后以“X 运算符 Y”的形式计算机出结果,再压加栈S中
·如果后缀表达式未读完,就重复上面过程,最后输出栈顶的数值则为结束
java中缀的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java中缀表达式转后缀表达式代码、java中缀的信息别忘了在本站进行查找喔。
发布于:2022-12-19,除非注明,否则均为
原创文章,转载请注明出处。