⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 postfix.java

📁 Convert infix to postfix and show each process in SVG
💻 JAVA
字号:
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.io.*;

public class Postfix {	
    static final int NUMBER = 0, OPERATOR = 1;   // values for kind.
	private Stack<Character> theStack;
	private Stack<Node> chkStack;
	private Stack<Node> picStack;
	private Stack<Node> copStack;
	private String output = "";
	String scan = "";
	int k = 1;
	int x = 512;
	int y = 970;
	int size = 0;
	double chk = 0;
	char chk2 = ' ';
    static int lx = 1, ly = 0, a = 0, s = 1;
		
public static void main(String[] args) throws IOException {
		String infixExp = "11 +2*4- 5/(2+3)";
	//	String infixExp = "11 +2*4- 5/3";
		System.out.println("Infix: " + infixExp);
		
		Postfix p = new Postfix(infixExp);
		System.out.println("Postfix: " + p );
		
  }
  
  public void Post2Bin(String in)throws IOException {
	  chkStack = new Stack<Node>();
	  picStack = new Stack<Node>();
	  copStack = new Stack<Node>();
	  for (int j = 0; j < in.length(); j++) {
		  char c = in.charAt(j);
		  char cn;
		  if ((j+1) < in.length()){
			  cn = in.charAt(j+1);
		  }else{
			  cn = 'y';
		  }
		  switch (c) {
			  case '+': 
			  case '-': 
			  case '*':	
			  case '/': 
						Node t1 = chkStack.pop();
						Node t2 = chkStack.pop();
						Node t3 = new Node(c, t1, t2);
						chkStack.push(t3);
						size -= 1;
						s+=1;
						break;
			  case ' ':
						break;
			  default: // must be an operand
						scan = scan + c;		
						if (cn == ' ' || cn == 'y'){
							double dDouble = Double.parseDouble(scan);
							Node t4 = new Node(dDouble);
							chkStack.push(t4);
							scan = "";
							size += 1;							
						}
						else{}
						break;
		  }		  
		  while (!chkStack.isEmpty()){
			  Node s = chkStack.pop();
			  picStack.push(s);
			  copStack.push(s);
		  }
		  while (!copStack.isEmpty()){
			  chkStack.push(copStack.pop());
		  }
		  
		  if (picStack.size() > 0 && size != picStack.size()){
				  prt(picStack);
				  while (!picStack.isEmpty()){
					  picStack.pop();
				  }
		  }
	  }
	  System.out.println();
  }

  public void prt(Stack<Node> in)throws IOException{
		  FileWriter svg = new FileWriter("PB"+k+".svg",true);
		  BufferedWriter out = new BufferedWriter(svg);
		  out.write("<?xml version=\"1.0\" standalone=\"no\"?>\n");	
		  out.write("<svg viewBox=\"0 0 1024 1024\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\">\n");	
		  out.write("<line x1=\"150\" y1=\"0\" x2=\"150\" y2=\"1024\" stroke='black' stroke-width='4' />\n");	
		  out.write("<line x1=\"1000\" y1=\"0\" x2=\"1000\" y2=\"1024\" stroke='black' stroke-width='4' />\n");	
		  out.write("<line x1=\"150\" y1=\"1020\" x2=\"1000\" y2=\"1020\" stroke='black' stroke-width='4' />\n");	
		  out.close();
			for (int i = 0;i < in.size();i++ ){
				Node t = in.pop();
				if (t.kind == NUMBER){
					FileWriter svg2 = new FileWriter("PB"+k+".svg",true);
					BufferedWriter out2 = new BufferedWriter(svg2);
					out2.write("<line x1=\"150\" y1=\""+(y-50)+"\" x2=\"1000\" y2=\""+(y-50)+"\" stroke='black' stroke-width='4' />\n");
					out2.close();
					noderTest(t,k,x,y);
					y -= 100;
				}
				else{
					y -= s*50;
					FileWriter svg2 = new FileWriter("PB"+k+".svg",true);
					BufferedWriter out2 = new BufferedWriter(svg2);
					out2.write("<line x1=\"150\" y1=\""+(y-50)+"\" x2=\"1000\" y2=\""+(y-50)+"\" stroke='black' stroke-width='4' />\n");
					out2.close();
					noderTest(t,k,x,y);
					y -= 100;
					lx = 1; ly = 0; a = 0;
				}
			  
		  }
		  y = 970;
		  FileWriter svg3 = new FileWriter("PB"+k+".svg",true);
		  BufferedWriter out3 = new BufferedWriter(svg3);
		  out3.write("</svg>");
		  out3.close();
		  k++;
	}

	public static void noderTest(Node node, int in,int xc ,int yc)throws IOException{
		Node t = node;
		FileWriter svg2 = new FileWriter("PB"+in+".svg",true);
		BufferedWriter out2 = new BufferedWriter(svg2);
		if ( t.kind == NUMBER) {
					out2.write("<circle cx=\""+xc+"\" cy=\""+yc+"\" r=\"30\" stroke='black' stroke-width='2'  fill='white' fill-opacity='.85' />\n");
					out2.write("<text class='Label' x=\""+(xc-10)+"\" y=\""+(yc+5)+"\">"+t.number+"</text>\n");
					out2.close();
					
		}
	     else { 
					out2.write("<circle cx=\""+xc+"\" cy=\""+yc+"\" r=\"30\" stroke='black' stroke-width='2'  fill='white' fill-opacity='.85' />\n");
					out2.write("<text class='Label' x=\""+(xc-10)+"\" y=\""+(yc+5)+"\">"+t.op+"</text>\n");
		 }
		if (t.left != null) {
			lx++;ly++;
			a = 0;
			out2.write("<line x1 = \""+(xc-20)+"\" y1 = \""+(yc+20)+"\" x2 = \""+(xc-(200/lx)+20 )+"\" y2 = \""+(yc+ly*50-20)+"\" stroke = \"black\" stroke-width = \"3\"/>\n");
			xc = xc - 200/lx;
			yc = yc + ly*50;
			noderTest(t.left,in,(xc),(yc));	
		}
		if (node.right != null) {
			if (a == 0)
			{
				xc = xc + 2*(200/lx);
				out2.write("<line x1 = \""+(xc-20)+"\" y1 = \""+(yc-20)+"\" x2 = \""+(xc-(200/lx)+20 )+"\" y2 = \""+(yc-ly*50+20)+"\" stroke = \"black\" stroke-width = \"3\"/>\n");
				a++;
			}
			else{
				lx--;
				if (lx == 3)
				{
					int c = ly;
					lx = 2;
					ly = 0;
					xc = 512 + 200/lx;
					yc = yc - ly*50;
					out2.write("<line x1 = \""+(xc-20)+"\" y1 = \""+(yc-20)+"\" x2 = \""+(xc-(200/lx)+20 )+"\" y2 = \""+(yc-30)+"\" stroke = \"black\" stroke-width = \"3\"/>\n");
					ly = 2;
				}
				else{
					xc = xc + 200/lx;
					yc = yc - ly*50;
					out2.write("<line x1 = \""+(xc-20)+"\" y1 = \""+(yc-20)+"\" x2 = \""+(xc-(200/lx)+20 )+"\" y2 = \""+(yc-ly*50+20)+"\" stroke = \"black\" stroke-width = \"3\"/>\n");
				}
					ly--;
			}			
			noderTest(t.right,in,(xc),(yc));
		}
		out2.close();
	}

  public Postfix(String in)throws IOException  {
	  theStack = new Stack<Character>();
	  for (int j = 0; j < in.length(); j++) {
		  char ch = in.charAt(j);
		  char ch2;
		  if ((j+1) < in.length()){
			  ch2 = in.charAt(j+1);
		  }else{
			  ch2 = 'y';
		  }
		  
		  switch (ch) {
			  case '+': // it's + or -
			  case '-': gotOper(ch, 1); // (precedence 1)
						break; 
			  case '*':	// it's * or /
			  case '/': gotOper(ch, 2); // go pop operators
						break;			// (precedence 2)
			  case '(':	theStack.push(ch);	// it's a left paren // push it
						break;
			  case ')':	gotParen();		// it's a right paren // go pop operators
						break;
			  case ' ':
						break;
			  default: // must be an operand
						output=output + " " +ch;
						while ((Character.isDigit(ch2))||(ch2=='.')){	//next Character isDigit
						output = output + ch2;
						j++;
						ch2 = in.charAt(j+1);
					//	try{ch2 = in.charAt(j+1);}						
					//	catch(Exception e){ch2='y';}					
						}	
						break;
		  }
	  }  
	  while (!theStack.isEmpty()){
		  output = output +" "+ theStack.pop();
	  }
	  output = output + " ";
	  Post2Bin(output);
  }

  public String  toString(){
	  return String.valueOf(output);
  }
  
  public void gotOper(char opThis, int prec1) {
	  while (!theStack.isEmpty()) {
		  char opTop = theStack.peek();
		  if (opTop == '(') { 
			  break;
		  }else{		// it's an operator // precedence of new op
			  int prec2;
			  if (opTop == '+' || opTop == '-')
				  prec2 = 1;
			  else 
				  prec2 = 2;
		//    else
		//		  prec2 = 0;
			  if (prec2 < prec1) {		// if prec of new op lessthan prec of old   
				  break;				// save newly-popped op
			  }else{
				  // prec of new not less
				  output = output +" "+ theStack.pop(); // than prec of old
			  }
		  }
	  }
	  theStack.push(opThis);
  }
  
  public void gotParen(){ 
	  while (theStack.peek() != '(') {
		  output = output + " " + theStack.pop(); 
	  }
	  theStack.pop();
  }
    
  class Stack<Item> implements Iterable<Item> {
    private int N;          // size of the stack
    private Node first;     // top of stack

    // helper linked list class
    private class Node {
        private Item item;
        private Node next;
    }

    // create an empty stack
    public Stack() {
        first = null;
        N = 0;
    }

    // is the stack empty?
    // number of elements on the stack
    public boolean isEmpty() { return first == null; }
    public int size()        { return N;             }


    // return most recently added item
    public Item peek() {
        return first.item;
    }


    // add an item to the stack
    public void push(Item item) {
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        N++;
    }

    // delete and return the most recently added item
    public Item pop() {
        if (isEmpty()) throw new RuntimeException("Stack underflow");
        Item item = first.item;        // save item to return
        first = first.next;            // delete first node
        N--;
        return item;                   // return the saved item
    }

    public Iterator<Item> iterator()  { return new StackIterator();  }

    // an iterator, doesn't implement remove() since it's optional
    private class StackIterator implements Iterator<Item> {
        private Node current = first;
        public boolean hasNext()  { return current != null;                     }
        public void remove()      { throw new UnsupportedOperationException();  }

        public Item next() {
            if (!hasNext()) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next; 
            return item;
        }
    }
  }
  class Node {                                      
    int kind;       // type of node
    double number;  // The value in a node
    char op;        // The operator in a node
    Node left;		// left node
    Node right;		// rightleft node

    Node(double val) {
       kind = NUMBER;
       number = val;
    }
    
    Node(char val) {
       kind = OPERATOR;
       this.op = val;
    }    

    Node(char op, Node right, Node left) {
       kind = OPERATOR;
       this.op = op;
       this.left = left;
       this.right = right;
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -