• Breaking News

    Funny Coder

    Funny coder is an open source web for interested programmer. It is a programming environment.It's a way where you can code with fun.

    Saturday, April 16, 2016

    Infix to Postfix Java source Code


    Full Source Code in java: Infix to postfix:



    1. import java.util.Scanner;
    2. import java.util.Stack;

    3. public class Infix2PostFix {
    4.     static int getPrecedence(char checkChar)
    5.     {
    6.         if(checkChar=='+'||checkChar=='-')
    7.             return 1;
    8.          if(checkChar=='*'||checkChar=='/')
    9.             return 2;
    10.          if(checkChar=='('||checkChar==')')
    11.             return 0;
    12.          return -1;


    13.     }

    14.     public static void main(String[] args) {
    15.        Stack<Character> stack=new Stack();
    16.        Scanner scanner =new Scanner(System.in);
    17.        String result="";
    18.        String inputStr=scanner.nextLine();

    19.        char[] inputCharArray=inputStr.toCharArray();
    20.        for(char chrac:inputCharArray)
    21.            System.out.println(chrac);

    22.        
    23.        for(int i=0;i<inputCharArray.length;i++)
    24.        {
    25.            char checkChar=inputCharArray[i];
    26.            if(checkChar!='+'&& checkChar!='-'&&checkChar!='/'&&checkChar!='*'&&checkChar!='('&&checkChar!=')')
    27.            {
    28.                result = result+checkChar;
    29.            }else
    30.            {
    31.                if(checkChar != '(' && checkChar != ')')
    32.                {
    33.                    if(stack.isEmpty())
    34.                    {
    35.                        stack.push(checkChar);
    36.                    }else
    37.                    {

    38.                     while(getPrecedence(stack.peek())>=getPrecedence(checkChar))
    39.                     {
    40.                      result=result+stack.pop();
    41.                      if(stack.isEmpty())
    42.                         break;
    43.                     }
    44.              stack.push(checkChar);
    45.                }

    46.                } else
    47.                {
    48.                    if(checkChar=='(')
    49.                        stack.push(checkChar);
    50.                    else
    51.                    {
    52.                        while(stack.peek()!='(')
    53.                        {
    54.                            result=result+stack.pop();
    55.                        }
    56.                        stack.pop();
    57.                    }
    58.                }
    59.        }


    60.     }
    61.        while(!stack.isEmpty())
    62.            result=result+stack.pop();

    63.        System.out.println(result);
    64. }

    65. }



    No comments:

    Post a Comment

    Fashion

    Beauty

    Travel