1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

infix to prefix , infix to postfix

Discussion in 'Java' started by SyferZookie, Nov 6, 2009.

  1. SyferZookie

    SyferZookie New Member

    Code:
    import java.io.*;
    import java.util.*;
    public class Mlab2
    {
    // initialize two stacks: operator and operand
    private static Stack operatorStack = new Stack();
    private static Stack operandStack = new Stack();
    // method converts infix expression to postfix notation
    private static String toPostfix(String infix)
    {
    StringTokenizer s = new StringTokenizer(infix);
    // divides the input into tokens for input
    String symbol, postfix = "";
    while (s.hasMoreTokens())
    // while there is input to be read
    {
    symbol = s.nextToken();
    // if it's a number, add it to the string
    if (Character.isDigit(symbol.charAt(0)))
    postfix = postfix + " " + (Integer.parseInt(symbol));
    else if (symbol.equals("("))
    // push "("
    {
    Character operator = new Character('(');
    operatorStack.push(operator);
    }
    else if (symbol.equals(")"))
    // push everything back to "("
    {
    while (((Character)operatorStack.peek()).charValue() != '(')
    {
    postfix = postfix + " " + operatorStack.pop();
    }
    operatorStack.pop();
    }
    else
    // print operatorStack occurring before it that have greater precedence
    {
    while (!operatorStack.empty() && !(operatorStack.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operatorStack.peek()).charValue()))
    postfix = postfix + " " + operatorStack.pop();
    Character operator = new Character(symbol.charAt(0));
    operatorStack.push(operator);
    }
    }
    while (!operatorStack.empty())
    postfix = postfix + " " + operatorStack.pop();
    return postfix;
    }
    // method evaulates postfix expression
    private static int evaluate(String postfix)
    {
    StringTokenizer s = new StringTokenizer(postfix);
    // divides the input into tokens for input
    int value;
    String symbol;
    while (s.hasMoreTokens())
    {
    symbol = s.nextToken();
    if (Character.isDigit(symbol.charAt(0)))
    // if it's a number, push it onto stack
    {
    Integer operand = new Integer(Integer.parseInt(symbol));
    operandStack.push(operand);
    }
    else // if it's an operator, operate on the previous two popped operandStack items
    {
    int op2 = ((Integer)operandStack.pop()).intValue();
    int op1 = ((Integer)operandStack.pop()).intValue();
    int result = 0;
    switch(symbol.charAt(0)){
    case '*': {
     result = op1 * op2; break;
     }
    case '+': {
     result = op1 + op2; break;
     }
    case '-': {
     result = op1 - op2; break;
     }
    case '/': {
     result = op1 / op2; break;
     }
    case '%': {
     result = op1 % op2; break;
     }
    case '^': {
     result = op1 ^ op2; break;
     }
    }
    Integer operand = new Integer(result);
    operandStack.push(operand);
    }
    }
    value = ((Integer)operandStack.pop()).intValue();
    return value;
    }
    // method compares operators to establish precedence
    private static int prec(char x){
    if (x == '+' || x == '-'){
    return 1;
    }
    else if (x=='^' && x == '*' || x == '/' || x == '%'){
    return 2;
    }
    else{
    return 0;
    }
    }
    
    public static void main(String args[]) throws IOException{
    String infix;
    BufferedReader keyboard = new BufferedReader (new InputStreamReader(System.in));
    
    System.out.print("Input a infix: ");
    infix = keyboard.readLine();
    
    System.out.println("Expression in postfix:" + toPostfix(infix));
    
    System.out.println("Evaluated expression: " + evaluate(toPostfix(infix)));
    }
    }
    
    
    error occured
    Code:
    Input a infix: 1+1
    Exception in thread "main" java.lang.NumberFormatException: For input string: "1
    +1"
            at java.lang.NumberFormatException.forInputString(NumberFormatException.
    java:48)
            at java.lang.Integer.parseInt(Integer.java:456)
            at java.lang.Integer.parseInt(Integer.java:497)
            at Mlab2.toPostfix(Mlab2.java:23)
            at Mlab2.main(Mlab2.java:125)
    
    
    before that it has a warning when i build it.
    Code:
    Note: D:\syfer\Mlab2.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    Process completed.
    
    and 1 more think
    i also need a help about my
    infix to prefix
     
  2. SyferZookie

    SyferZookie New Member

    Code:
    import java.io.*;
    import java.util.*;
    public class Mlab2{
    private static Stack operatorStack = new Stack ();
    private static Stack operandStack = new Stack ();
    
    private static String toPostfix(String infix){
    StringTokenizer s = new StringTokenizer(infix);
    String symbol, postfix = "";
    while (s.hasMoreTokens()){
    symbol = s.nextToken();
    if (Character.isDigit(symbol.charAt(0))){
    postfix = postfix + " " + (Integer.parseInt(symbol));
    }else if (symbol.equals("(")){
    Character operator = new Character('(');
    operatorStack.push(operator);
    }else if (symbol.equals(")")){
    while (((Character)operatorStack.peek()).charValue() != '('){
    postfix = postfix + " " + operatorStack.pop();
    }
    operatorStack.pop();
    }else{
    while (!operatorStack.empty() && !(operatorStack.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operatorStack.peek()).charValue()))
    postfix = postfix + " " + operatorStack.pop();
    Character operator = new Character(symbol.charAt(0));
    operatorStack.push(operator);
    }}
    while (!operatorStack.empty())
    postfix = postfix + " " + operatorStack.pop();
    return postfix;
    }
    private static String toPrefix(String infix){
     StringTokenizer pre = new StringTokenizer(infix);
     
     String symbol1 , prefix= "";
     while(pre.hasMoreTokens()){
      symbol1 = pre.nextToken();
      
      if(Character.isDigit(symbol1.charAt(0))){
       prefix = prefix+ " " +(Integer.parseInt(symbol1));
       }else if(symbol1.equals("(")){
        Character operand = new Character('(');
        operandStack.push(operand);
        }else if(symbol1.equals(")")){
         while (((Character)operandStack.peek()).charValue()!= '('){
          prefix = prefix + " " + operandStack.pop();
         }
         operandStack.pop();
        }else{
         while(!operandStack.empty()&&!(operandStack.peek()).equals("(")
         && prec(symbol1.charAt(0))<= prec(((Character)operandStack.peek()).charValue()))
         
         prefix = prefix + " "+ operandStack.pop();
         Character operand = new Character(symbol1.charAt(0));
         operandStack.push(operand);
        }}
        while(!operandStack.empty())
        prefix = prefix + " " +operandStack.pop();
        return prefix;
       }
     
    private static int evaluate(String postfix){
    StringTokenizer s = new StringTokenizer(postfix);
    int value;
    String symbol;
    while (s.hasMoreTokens()){
    symbol = s.nextToken();
    if (Character.isDigit(symbol.charAt(0))){
    Integer operand = new Integer(Integer.parseInt(symbol));
    operandStack.push(operand);
    }else {
    int op2 = ((Integer)operandStack.pop()).intValue();
    int op1 = ((Integer)operandStack.pop()).intValue();
    int result = 0;
    switch(symbol.charAt(0)){
    case '*': {
     result = op1 * op2; break;
     }
    case '+': {
     result = op1 + op2; break;
     }
    case '-': {
     result = op1 - op2; break;
     }
    case '/': {
     result = op1 / op2; break;
     }
    case '%': {
     result = op1 % op2; break;
     }
    case '^': {
     result = op1 ^ op2; break;
     }
    }
    Integer operand = new Integer(result);
    operandStack.push(operand);
    }
    }
    value = ((Integer)operandStack.pop()).intValue();
    return value;
    }
    private static int prec(char x){
    if (x == '+' || x == '-'){
    return 1;
    }
    else if (x=='^' && x == '*' || x == '/' || x == '%'){
    return 2;
    }
    else{
    return 0;
    }
    }
    public static void main(String args[]) throws IOException{
    BufferedReader keyboard = new BufferedReader (new InputStreamReader(System.in));
    String infix;
    System.out.print("Input a infix: ");
    infix = keyboard.readLine();
    System.out.println("Expression in postfix:" + toPostfix(infix));
    System.out.println("Expression in prefix: " + toPrefix(infix));
     
    }
    }
     

    code has been edited to this
    but my problem now is
    the answer im looking for is not appearing like

    i input'd
    a infix : a+b
    the answers are:

    POSTFIX: a
    PREFIX: a
    which are not the real answer.

    kindly please help me out
     

Share This Page