▶ 뭉충닷컴
 
mungchung.com login
Site Search
My Space
주절주절...
공부방
쥔장소개
Board
자유게시판
유용한 정보
자료실
Programming
강좌 & Articles
Spring 3.0
프로그래밍 Tip
   -ASP
   -PHP
   -JavaScript
   -HTML
   -Java/JSP
   -Database
   -Crystal Report
   -Visual Basic
   -이클립스
   -리눅스
   -기타
Windows API (VB)
Spread Sheet 7.0
컴퓨터활용 Tip
Other things
StarCraft 전략
StarCraft 문서
김용(金庸)
Son Q & Dieda

java, infix를 postfix로 만들기

JAVA 조회 수 11919 추천 수 0 2007.04.05 14:44:17
기존 postfix가 연산을 못해서 다시 올린다...기존 소스는 아래있음
참고로 네이버 어디선가 퍼옴


import java.io.*;
import java.util.*;

class ListNode
{
  public Object data;
  public ListNode link;
}

class ListStack
{
  private ListNode top;
  
  public boolean isEmpty() {
    return (top == null);
  }
  
  public void push(Object x) {
    ListNode newNode = new ListNode();
    newNode.data = x;
    newNode.link = top;
    top = newNode;
  }
  
  public Object pop() {
    if (isEmpty()) return null;
    
    Object Item = top.data;
    top = top.link;
    
    return Item;
  }
  
  public void remove() {
    if (isEmpty()) return;
    
    top = top.link;
  }
  
  
  public Object peek() {
    if (isEmpty()) return null;
    
    return top.data;
  }
}

class Postfix
{
  private StringBuffer postfix;
  private String rawString;
  private ListStack listStack;
  
  public Postfix(String s) throws Exception {
    rawString = s;
    postfix = new StringBuffer();
    listStack = new ListStack();
    
    if (!makePostfix())
      throw new Exception("error : " + rawString);
  }
  
  public String getPostfix() {
    return postfix.toString().substring(0, postfix.toString().length() - 1);
  }
  
  public String getRawString() {
    return rawString;
  }
  
  public static boolean isOperator(char ch) {
    return ( ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%' || ch == '^' );
  }
  
  private boolean makePostfix() {
    char ch, left;
    
    if (rawString.length() == 0) return false;
    
    for (int i = 0; i < rawString.length(); i++) {
      ch = rawString.charAt(i);
      
      if (ch == '(' || ch == '{' || ch == '[') {
        listStack.push(String.valueOf(ch));
      } else if (ch == ')') {
        try {
          while (!((String)listStack.peek()).equals("(")) {
            if (listStack.isEmpty()) return false;
            
            postfix.append((String)listStack.pop());
            postfix.append(" ");
          }
        } catch (NullPointerException e) {
          return false;
        }
        
        listStack.pop();
      } else if (ch == '}') {
        try {
          while (!((String)listStack.peek()).equals("{")) {
            if (listStack.isEmpty()) return false;
            
            postfix.append((String)listStack.pop());
            postfix.append(" ");
          }
        } catch (NullPointerException e) {
          return false;
        }
        
        listStack.pop();
      } else if (ch == ']') {
        try {
          while (!((String)listStack.peek()).equals("[")) {
            if (listStack.isEmpty()) return false;
            
            postfix.append((String)listStack.pop());
            postfix.append(" ");
          }
        } catch (NullPointerException e) {
          return false;
        }
        
        listStack.pop();
      } else if (ch >= '0' && ch <= '9') {
        do {
          postfix.append(String.valueOf(ch));
          
          try {
            ch = rawString.charAt(++i);
          } catch (StringIndexOutOfBoundsException e) {
            ch = ' ';
          }
        } while (ch >= '0' && ch <= '9');
        
        postfix.append(" ");
        i--;
      } else if (isOperator(ch)) {
        while (!listStack.isEmpty() && getPriority((String)listStack.peek()) >= getPriority(String.valueOf(ch))) {
          postfix.append((String)listStack.pop());
          postfix.append(" ");
        }
        
        listStack.push(String.valueOf(ch));
      } else if (ch == '.') {
        postfix.deleteCharAt(postfix.toString().length() - 1);
        postfix.append(String.valueOf('.'));
      } else if (ch == ' ' || ch == '\t') {
      } else {
        return false;
      }
    }
    
    while (!listStack.isEmpty())
      if (isOperator(((String) listStack.peek()).charAt(0))) {
        postfix.append(listStack.pop());
        postfix.append(" ");
      } else {
        return false;
      }
      
    return true;
  }
  
  private int getPriority(String operator) {
    if (operator.equals("(") || operator.equals("{") || operator.equals("["))
      return -1;
    else if (operator.equals("+") || operator.equals("-"))
      return 1;
    else
      return 2;
  }
}


public class Calculator
{
  private String postfix;
  private ListStack listStack;
  private double value;
  
  public Calculator(String s){
    postfix = s;
    listStack = new ListStack();
    value = 0;
  }
  
  public double getPostfixValue(){
    StringTokenizer token = new StringTokenizer(postfix, " ");
    
    while(token.hasMoreElements()) {
      String operator = token.nextToken();
      
      if (Postfix.isOperator(operator.charAt(0))) {
        double op1 = ((Double) listStack.pop()).doubleValue();
        double op2 = ((Double) listStack.pop()).doubleValue();
        
        value = calculate(operator, op1, op2);
        
        listStack.push(new Double(value));
      } else {
        listStack.push(Double.valueOf(operator));
      }
    }
    
    return ((Double) listStack.pop()).doubleValue();
  }
  
  private double calculate(String operator, double op1, double op2){
    switch(operator.charAt(0)){
      case '+' : return (op2 + op1);
      case '-' : return (op2 - op1);
      case '*' : return (op2 * op1);
      case '/' : return (op2 / op1);
      case '%' : return (op2 % op1);
      case '^' : return Math.pow(op2, op1);
      default :
        System.out.println("illegal operation");
        System.exit(1);
    }
    return 0;
  }
  
  public static void main(String[] args) {
    Postfix postfix = null;
    Calculator calc = null;
    
    try {

      //String rawString = "2**3**2";
      String rawString = "12+23-3*(16+48)+48";
      postfix = new Postfix(rawString);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      System.exit(1);
    }
    
    System.out.println("infix : " + postfix.getRawString());
    System.out.println("postfix : " + postfix.getPostfix());
    
    calc = new Calculator(postfix.getPostfix());
    System.out.println("값 : " + calc.getPostfixValue());
  }
}



=========================================================================
==== 계산못하는 postfix 변환-_-
=========================================================================



http://www.java2s.com/Code/Java/Collections-Data-Structure/Convertsinfixarithmeticexpressionstopostfix.htm




import java.io.IOException;

public class InToPost {
  private Stack theStack;

  private String input;

  private String output = "";

  public InToPost(String in) {
    input = in;
    int stackSize = input.length();
    theStack = new Stack(stackSize);
  }

  public String doTrans() {
    for (int j = 0; j < input.length(); j++) {
      char ch = input.charAt(j);
      switch (ch) {
      case '+':
      case '-':
        gotOper(ch, 1);
        break; //   (precedence 1)
      case '*': // it's * or /
      case '/':
        gotOper(ch, 2); // go pop operators
        break; //   (precedence 2)
      case '(': // it's a left paren
        theStack.push(ch); // push it
        break;
      case ')': // it's a right paren
        gotParen(ch); // go pop operators
        break;
      default: // must be an operand
        output = output + ch; // write it to output
        break;
      }
    }
    while (!theStack.isEmpty()) {
      output = output + theStack.pop();

    }
    System.out.println(output);
    return output; // return postfix
  }

  public void gotOper(char opThis, int prec1) {
    while (!theStack.isEmpty()) {
      char opTop = theStack.pop();
      if (opTop == '(') {
        theStack.push(opTop);
        break;
      }// it's an operator
      else {// precedence of new op
        int prec2;
        if (opTop == '+' || opTop == '-')
          prec2 = 1;
        else
          prec2 = 2;
        if (prec2 < prec1) // if prec of new op less
        { //    than prec of old
          theStack.push(opTop); // save newly-popped op
          break;
        } else
          // prec of new not less
          output = output + opTop; // than prec of old
      }
    }
    theStack.push(opThis);
  }

  public void gotParen(char ch){
    while (!theStack.isEmpty()) {
      char chx = theStack.pop();
      if (chx == '(')
        break;
      else
        output = output + chx;
    }
  }

  public static void main(String[] args) throws IOException {
    String input = "1+2*4/5-7+3/6";
    String output;
    InToPost theTrans = new InToPost(input);
    output = theTrans.doTrans();
    System.out.println("Postfix is " + output + '\n');

  }
  class Stack {
    private int maxSize;
  
    private char[] stackArray;
  
    private int top;
  
    public Stack(int max) {
      maxSize = max;
      stackArray = new char[maxSize];
      top = -1;
    }
  
    public void push(char j) {
      stackArray[++top] = j;
    }
  
    public char pop() {
      return stackArray[top--];
    }
  
    public char peek() {
      return stackArray[top];
    }
  
    public boolean isEmpty() {
      return (top == -1);
    }
  }

}

문서 첨부 제한 : 0Byte/ 2.00MB
파일 크기 제한 : 2.00MB (허용 확장자 : *.*)
List of Articles
번호 제목 글쓴이 날짜 조회 수
15 JAVA 이클립스에 톰캣서버 연동하기 file 뭉충닷컴 2008-03-21 10426
14 JAVA while문 이용하여 텍스트파일에 쓰여진 글 읽기 뭉충닷컴 2008-02-26 9476
13 JAVA 오늘 날짜 구하기 뭉충닷컴 2008-02-22 11268
12 JAVA Java 형변환 정리 뭉충닷컴 2008-02-06 13414
11 JAVA HashMap, TreeMap, Hashtable 사용법 정리 file 뭉충닷컴 2008-01-29 29660
10 JAVA value 값이 Ljava.lang.String 형일 때 실제 값 보기 뭉충닷컴 2008-01-29 10903
9 JAVA 톰캣(tomcat) 4.x 버젼에서 한글/UTF-8 사용하기 file 뭉충닷컴 2008-01-28 8486
8 JAVA RMI, IIOP에 대한 설명 뭉충닷컴 2008-01-22 6871
7 JAVA 자바의 직렬화(Serializable) 설명 뭉충닷컴 2008-01-18 7013
6 JAVA BLOB으로 저장된 사진정보 파일로 받기 이영진 2007-08-31 14790
5 JAVA classes12와 ojdbc14의 CLOB 처리 비교 이영진 2007-08-30 13757
4 JAVA classes12와 ojdbc14 connection 선언시 차이 [1] 이영진 2007-08-30 9054
» JAVA java, infix를 postfix로 만들기 file 뭉충닷컴 2007-04-05 11919
2 JAVA "==" 과 "equals()" 의 차이점 뭉충닷컴 2003-11-04 6817
1 JAVA split와 StringTokenizer 비교 뭉충닷컴 2003-11-04 9492