In: Computer Science
A formula with a positive integer (less than 32 bits) and a
positive decimal (number with decimal points) is expressed in the
median formula. Change the given median to postfix and write a
program that outputs the results of the calculation.
operand ::= positive integer or positive error
Positive integer ::= A number expressed as less than 32 bits
consisting of 0 to 9.
Positive integer representation of 0, 0100, 00934, 1056, 65535 is
allowed
Positive decimal ::= Positive integer and decimal point (.) and
positive integer number
A positive decimal representation of 0, 000.0100, 0.0001054,
0065.535, 1000.32 is allowed
Operator ::= '+', '-', '*', '/', '^', 'u' means unary operator -
(negative sign)
The rest are all binary operators.
(1) A median formula containing a positive integer and a decimal
number is entered.
(2) Change the entered median to the post-modality and output the
correct formula.
(3) If the median formula is reasonable, calculate the modified
formula and output the result.
Submission:
Output through program source and input example
e.g. infix : (15+5)* (15+u5) // Actual formula is (15+5)*
(15+5)
Postfix: 15 5 + 15 5 u + *
Result value = 200
The input infix : 003.14 * 05^2 // actual formula
Postfix: 3.14 5 2 ^ *
Result value = 78.5
The input infix : (13.75 – 06.25)/u2 // The actual formula is
(13.75 – 6.25)/(-2)
Postfix: 13.75 6.25 - 2 u /
Result value = -3.75
Entered infix : (13.2 – 3.2)/2* (5.6 + u2.6) + 3)
Output: This formula cannot be calculated.
Entered infix : 2* 5.6 – 3.14*-4
Output: Unacceptable number representation. (-4)
Program :
Java classes : Main.java, Arithmetic.java
put these both files in the same folder
Main.java
import java.util.*;
class Main
{
  public static void main(String[] args) 
  {
    String exp;
    Scanner sc = new Scanner(System.in);
    while(true){
      //Enter the infix expression
      System.out.print("\nEnter Infix expression : ");
      exp = sc.nextLine();
      System.out.println("Entered Infix : "+exp);
      //creating an instance of Arithmetic
      Arithmetic a = new Arithmetic(exp);
      //if isReasonable expression then calculate it
      if(a.isReasonable())
      {
        a.postfixExpression();
        System.out.println("Postfix : "+ a.getPostfix());
        a.evaluateExp();
        System.out.println("Result value : "+a.getResult());
      } 
      //asking for continue to the program or not
      System.out.println("Do you want to continue ? y or n : ");
      char ans = sc.next().charAt(0);
      if(ans != 'y' && ans !='Y'){
        break;
      }
      sc.nextLine();
    } 
  }
}
Arithmetic.java
import java.util.*;
public class Arithmetic
{
  //to keep all tokens generated from the expression
  private ArrayList<String> tokens=new ArrayList<String>();  
  private String postfix;  // to store the postfix expression
  private double result;  //calculated result
  //constructor taking the input expression string
  public Arithmetic(String expression)
  {
    //Generating the tokens present in the expression
    String tempTokens[] = expression.split("");  // split on the basis of spaces
                String temp = "";
                for(int i=0; i<tempTokens.length; i++) 
    {
      //if any operator or ( or  ) comes then add the temp to the tokens containing the operand string
                        if(tempTokens[i].equals("(") || tempTokens[i].equals(")") || tempTokens[i].equals(" ") || isOperator(tempTokens[i])) 
      {
        if(!temp.equals("")){
          double d = Double.parseDouble(temp);
          //if operand is integer then store its string integer into tokens
          //else add as string double
          if(d == (int)d){
            int d2 = (int)d;
            tokens.add(String.valueOf(d2));
          }else{
            tokens.add(String.valueOf(d));
          }
          //make the temp empty again to make the next operand
          temp = "";
        }
        if(!tempTokens[i].equals(" "))
                                 tokens.add(tempTokens[i]);  
                        }
      //otherwise add the portion in the temp string to get the complete operand
      else
      {
        temp = temp + tempTokens[i];
        //if i is the last index of tempTokens then simply add the temp to tokens
        if(i==tempTokens.length-1)
          tokens.add(temp);
      }
                }
  }
  double getResult()
  {
    return result;
  }
  String getPostfix()
  {
    return postfix;
  }
  //method to check that the expression is balanced or not
  //parenthesis matching using stack and check for number representation.
  public boolean isReasonable()
  {
    Stack<String> s=new Stack<String>();
    String prev = "";
    for(int j = 0; j<tokens.size(); j++)
    {
      String i = tokens.get(j);
      //if token is - then check for its representation
      if(i.equals("-") && (prev.equals("(") || isOperator(prev) || prev.equals("")) ) 
      {
        System.out.println("Output : Unacceptable number representation.(-"+tokens.get(j+1)+")");
        return false;
      }
      if(i.equals("("))
        s.push(i);
      else if(i.equals(")"))
      {
        if(s.empty())
        {
          //nUnbalanced Paranthesis
          System.out.println("Output : This formula cannot be calculated");
          return false;
        }
        s.pop();
      }
      prev  =i;
    }   
    if(s.empty())
    {
      //Balanced parenthesis
      return true;
    }
    System.out.println("Output : This formula cannot be calculated");
    return false;
  }
  //method to find the post fix form of the given expression
  //with the help of stack datastructure
  //infix to postfix conversion
  public void postfixExpression()
  {
    Stack<String> s=new Stack<String>();
                String y;
                this.postfix="";   //p==postfix expression
                tokens.add(")");
                s.push("(");
    
                for(String i: tokens) 
    {
      //case 1 : if parenthesis is left
      //then simply push it onto the stack
                        if(i.equals("("))
      {
                                s.push(i);
                        }
      //case 2 :if parenthesis is right
      //then pop from the stack util it reaches a left paraenthesis and add this popped elements to the postfix form.
      else if(i.equals(")"))
      {
                                y=s.pop();
                                while(!y.equals("("))
                                {
                                        this.postfix=this.postfix+y+" ";
          if(!s.empty())
                                          y=s.pop();
                                }
                        }
      //case 3 : if token is operator
      else if(isOperator(i))
      {
        //pop util conditions are met inside
        while(true)
        {
          y = s.pop();
          //stop if y is left parenthesis
          if(y.equals("("))
          {
            s.push(y);
            s.push(i);
            break;
          }
          else if(precedence(y)>=precedence(i))
          {
            this.postfix = this.postfix + y +" ";
          }
          //stop if precedence of the token is higher than top of stack
          else
          {
            s.push(y);
            s.push(i);
            break;
          }
        }
                        }
      //add to postfix if token is operand
      else
      {
                                this.postfix=this.postfix+i+" ";
                        }
                }
    //remaining operators added to the postfix form except ( or )
                while(!s.empty()) 
    {
                        y=s.pop();
                        if(!y.equals("(") && !y.equals(")")) 
      {
                                this.postfix += y+" ";
                        }
                }
  }
  //method to evaluate the actual value or calculation
  //postfix expression evaluation using stack
  public void evaluateExp()
  {
    String token[] = postfix.split(" ");
                
                Stack<Double> s=new Stack<Double>();
                double t1=0,t2=0;
                for(String  i:token) 
    {
      //if the token is operator
                        if(isOperator(i))
      {
        //if operator is unary u
        //pop the top element and push it back by making it negative
        if(i.equals("u"))
        {
          s.push(-1*s.pop());
        }
        else{
          //for binary operators
          //pop top 2 elements from the stack and calculate the result and then push back the result into the stack
          try{
            t1=s.pop();
            t2=s.pop();
          }catch(Exception e){
            System.out.println("\nmalformed postfix expression occured!");
            this.result =  Integer.MIN_VALUE;
          }
          s.push(calculate(t2,i,t1));  //i == operator
        }
        
                        }
      //else simply push into the stack by making it as double type
      else
      {
        s.push(Double.valueOf(i));
                        }
                }
    //taking the final result in result variable
                this.result=1;
                while(!s.empty()) {
                        this.result = this.result * s.pop();
                }
  }
  //for actual calculation with binary operators
        private double calculate(double x,String operator,double y)
        {
                double result=0;
                switch(operator)
                {
                        case "-":
                                result= x-y;
                                break;
                        case "+":
                                result= x+y;
                                break;
                        case "*":
                                result= x*y;
                                break;
                        case "/":
                                result= x/y;
                                break;
                        case "^":
                                result= Math.pow(x,y);
                                break;
                        default :
                                result= 0;
                }
                return result;
        }
  //precedence method
        private int precedence(String x)
        {
                int p=10;
                switch(x) {
      case "+":
        p=1;
        break;
      case "-":
        p=2;
        break;
      case "*":
        p=3;
        break;
      case "/":
        p=3;
        break;
      case "^":
        p=4;
        break;
      case "u":
        p = 5;
        break;
                }
                return p;
        }
        
        //operator checking
        public boolean isOperator(String x)
        {
                if(x.equals("+") || x.equals("-") || x.equals("*") || x.equals("/") || x.equals("^") || x.equals("u"))
                        return true;
                else 
                        return false;
        }
}
Output screen shots :

Program screenshots :










