postfix.java
来自「Java编写后缀表达式计算器, 用于输出生成后缀表达式, 程序包含完整的Docu」· Java 代码 · 共 96 行
JAVA
96 行
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package postfix;import java.io.*;import exception.SyntaxException;import exception.LexException;import exception.ExceptionContainer;/** * 老师给的代码,经过必要的改造 * @author zouhao */class Parser { static int lookahead; int index; String input; BufferedReader keyboard; public Parser() throws IOException { keyboard = new BufferedReader(new InputStreamReader(System.in)); input = keyboard.readLine(); index = 0; lookahead = input.charAt(index); } void expr() throws IOException { term(); rest(); } void rest() throws IOException { try{ while(lookahead != '\n'){ if (lookahead == '+') { match('+'); term(); System.out.write('+'); if(lookahead != '\n'){continue;} else {break;} } else if (lookahead == '-') { match('-'); term(); System.out.write('-'); if(lookahead != '\n'){continue;} else {break;} } else if(Character.isDigit((char)lookahead)){ throw new SyntaxException(index,"miss operator"); } else throw new LexException(index); } } catch (SyntaxException e){} catch (LexException e){} } void term() throws IOException { try {if (lookahead == '+'||lookahead == '-') { throw new SyntaxException(index,"miss operand"); }else if(Character.isDigit((char)lookahead)) { System.out.write((char)lookahead); match(lookahead); } else throw new LexException(index); } catch (SyntaxException e){} catch (LexException e){} } void match(int t) throws IOException { if (lookahead == t) { if(index<input.length()-1) { index++; lookahead = input.charAt(index); } else lookahead = '\n'; } else{ } }}public class Postfix { public static void main(String[] args) throws IOException { System.out.println("Input an infix expression and output its postfix notation:"); Parser parser = new Parser(); parser.expr(); ExceptionContainer temp = ExceptionContainer.getinstance(); temp.printexception(parser.input); System.out.println("\nEnd of program."); }}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?