Question

In: Computer Science

A formula with a positive integer (less than 32 bits) and a positive decimal (number with...

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)

Solutions

Expert Solution

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 :


Related Solutions

A) Fill in the blanks. (Enter an exact positive number as an integer, fraction, or decimal.)...
A) Fill in the blanks. (Enter an exact positive number as an integer, fraction, or decimal.) In a normal distribution, x = 3 and z = −1.19. This tells you that x = 3 is ________ standard deviations to the _____ (left or right) of the mean B) Fill in the blanks. (Enter an exact positive number as an integer, fraction, or decimal.) In a normal distribution, x = −2 and z = 6. This tells you that x =...
Each of two players chooses a positive integer. If player i's integer is greater than player j's integer and less than three times this integer, then player j pays $1 to player i.
Question is based off of Game Theory Mixed strategy and Pure strategy Nash EquilibriumEach of two players chooses a positive integer. If player i's integer is greater than player j's integer and less than three times this integer, then player j pays $1 to player i. If player i's integer is at least three times greater than player j's integer, then player i pays $1 to player j. If the integers are equal, no payment is made. Each player's preferences...
Write a Java program to convert decimal (integer) numbers into their octal number (integer) equivalents. The...
Write a Java program to convert decimal (integer) numbers into their octal number (integer) equivalents. The input to the program will be a single non-negative integer number. If the number is less than or equal to 2097151, convert the number to its octal equivalent. If the number is larger than 2097151, output the phrase “UNABLE TO CONVERT” and quit the program. The output of your program will always be a 7-digit octal number with no spaces between any of the...
Write a Java program to convert decimal (integer) numbers into their octal number (integer) equivalents. The...
Write a Java program to convert decimal (integer) numbers into their octal number (integer) equivalents. The input to the program will be a single non-negative integer number. If the number is less than or equal to 2097151, convert the number to its octal equivalent. If the number is larger than 2097151, output the phrase “UNABLE TO CONVERT” and quit the program. The output of your program will always be a 7-digit octal number with no spaces between any of the...
Consider all positive integers less than 100. Find the number of integers divisible by 3 or...
Consider all positive integers less than 100. Find the number of integers divisible by 3 or 5? Consider strings formed from the 26 English letters. How many strings are there of length 5? How many ways are there to arrange the letters `a',`b', `c', `d', and `e' such that `a' is not immediately followed by`e' (no repeats since it is an arrangement)?
Write a function decimalToBinary(n) that converts a positive decimal integer n to a string representing the...
Write a function decimalToBinary(n) that converts a positive decimal integer n to a string representing the corresponding binary number. Do the conversion by repeatedly dividing the number n by 2 using integer division, keepting track of the remainders, until the number is reduced to 0. The remainders written in reverse order form the binary number string. Do integer division of 5 by 2, so that N//2 is 2 with remainder 1. Now divide 2 by 2 to get 1 with...
32. An example of a favorable variance is ________. A) actual revenues are less than expected...
32. An example of a favorable variance is ________. A) actual revenues are less than expected revenues B) actual expenses are less than expected expenses C) actual material prices are greater than expected material prices D) expected labor costs are less than actual labor costs 36. The activity-based budgeting system emphasizes ________. A) the resources needed by a company B) the preparation of budgets by function C) the attainment of long-range goals D) activities and their consumption of resources 39....
1b) Suppose z is any positive even integer. Write a formula in terms of z that...
1b) Suppose z is any positive even integer. Write a formula in terms of z that gives the total number of palindromes of length z using characters from a set that contains 40 different symbols. A palindrome is a string of characters that are the same from left to right and right to left. 1c) Suppose z is any positive odd integer. Write a formula in terms of z that gives the total number of palindromes of length z using...
Numeric responses must be either an integer (if exact) or a real number with three decimal...
Numeric responses must be either an integer (if exact) or a real number with three decimal places, with the least significant number rounded. Do not use commas. If there are units, the integer part must be between 1 and 999. Use the following units: Ohm, kOhm, mOhm resistors, etc. Conductances: S, mS, MS, etc. Voltage: V, kV, mV, MV, etc. Current: A, mA, kA, uA, nA, etc. Power: W, mW, kW, uA, pW, etc. Time: s, hrs, ks, ms, etc....
1a. What is the largest positive and negative number that you could represent with 7 bits...
1a. What is the largest positive and negative number that you could represent with 7 bits using signed magnitude? Show your work. 1c. Solve the following decimal notation equation using 8-bit binary numbers and 2’s complement notation: 69 - 7 = Show your work
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT