Question

Using Java- Write a program that takes an arithmetic expression in an infix form, converts it...

Using Java- Write a program that takes an arithmetic expression in an infix form, converts it to a postfix form and then evaluates it. Use linked lists for the infix and postfix queues and the operator and value stacks. You must use sperate Stack and Queue classes with a driver class to run the program.

example Input : 111++
Output : (1+ (1+ 1))
Answer: 3
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.Stack;

import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class B1Work {

   public static boolean precedence(char first, char second) {

       if (second == '(' || second == ')')
           return false;
       if ((first == '*' || first == '/') && (second == '+' || second == '-'))
           return false;
       else
           return true;

   }
  
   public static java.awt.Point highestPoint( List<java.awt.Point> points){
       Iterator < java.awt.Point> pointIterator = points.iterator();
      
       java.awt.Point highestPoint = null;
      
       while(pointIterator.hasNext()) {
           java.awt.Point p = pointIterator.next();
           if(highestPoint == null)
               highestPoint = p;
           else if(highestPoint != null && p.getY() > highestPoint.getY() )
               highestPoint = p;
       }
      
      
       return highestPoint;

   }
  
  
public class Outer{
   int data = 5;
   public void displayString() {
       class InnerClass1{
           int data2 = 10;
           public String getString() {
               return "Outer:" + data + ", Inner:" + data2;
           }
          
       }
      
       InnerClass1 ic = new InnerClass1();
       System.out.println(ic.getString());
      
   }
  
  
   int allEvenBits(int x) {
      
      
       int mask = 0xAAAAAAAA;
      
       int ans = x | mask ;
      
       return ~ans;
   }
   void Test(){
       displayString();
   }
  
  
  
  
}
public static String infixToPostfix(String infix) {
/*
* Convert an infix math formula to postfix format
* Infix format will always include parens around any two values and a symbol
* You will not need to imply any PEMDAS rules besides parens
* EXAMPLES:
* infix: (1+2) postfix: 12+
* infix: (1+(2-3)) postfix: 123-+
* infix: ((1+2)-3) postfix: 12+3-
* infix: ((1+2)-(3*4)) postfix: 12+34*-
*/
   char character[] = infix.toCharArray();
       Stack<Character> st = new Stack<Character>();
       for (int i = 0; i < character.length; i++) {
           if (character[i] == '(')
               st.push(character[i]);
           if (character[i] == ')') {

               if (st.isEmpty()) {
                   return "No matching open parenthesis error";
               }
               st.pop();

           }

       }

       if (!st.isEmpty())
           return "No matching close parenthesis error";

       // initialize the resulting postfix string
       String postfixString = "";

       // initialize the stack
       Stack<Character> stack1 = new Stack<Character>();

       // Obtain the character at index i in the string
       for (int i = 0; i < infix.length(); i++) {
           char ch = infix.charAt(i);

           if (Character.isLetter(ch) || Character.isDigit(ch))

               postfixString = postfixString + ch;

           else if (ch == '(') {

               stack1.push(ch);

           } else if (ch == ')') {

               while (stack1.peek() != '(') {

                   postfixString = postfixString + stack1.pop();

               }

               stack1.pop();

           } else {

               while (!stack1.isEmpty() && !(stack1.peek() == '(') && precedence(ch, stack1.peek()))

                   postfixString = postfixString + stack1.pop();

               stack1.push(ch);

           }

       }

       while (!stack1.isEmpty())

           postfixString = postfixString + stack1.pop();

       return postfixString;
}


public static boolean isCharacter(char ch) {
return (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') || Character.isDigit(ch);
}
public static String postfixToInfix(String postfix) {
/*
* Convert a postfix math formula to an infix format
* See above for conversion examples
* Make sure to include parens in the infix format
*
*
*/
     
     
   Stack<String> stack = new Stack<String>();
     
   for (int i = 0; i < postfix.length(); i++)
   {
   if (isCharacter(postfix.charAt(i)))
       stack.push(postfix.charAt(i) + "");
   else
   {
   String operator1 = stack.peek();
   stack.pop();
   String operator2 = stack.peek();
   stack.pop();
   stack.push("(" + operator2 + postfix.charAt(i) +
           operator1 + ")");
   }
   }
   return stack.peek();
}

public static double solvePostfix(String s) {
// Stack<Integer> stack = new Stack<>();
/*
* Use a Stack to help solve a postfix format formula for the numeric answer
* Order of operations is implied by where symbols/numbers exist
* EXAMPLES
* postfix: 12+ = 3
* postfix: 123-+ = 0 :: 2-3 = -1 :: 1 + (-1) = 0
*/
  
Stack<Double> postfix = new Stack<Double>();
       for (int i = 0; i < s.length(); i++) {
           char c = s.charAt(i);

           if (Character.isDigit(c))
               postfix.push((double) (c - '0'));
           else {
               double val1 = postfix.peek();
               postfix.pop();
               double val2 = postfix.peek();
               postfix.pop();

               switch (c) {
               case '+':
                   postfix.push(val2 + val1);
                   break;

               case '-':
                   postfix.push(val2 - val1);
                   break;

               case '/':
                   postfix.push(val2 / val1);
                   break;

               case '*':
                   postfix.push(val2 * val1);
                   break;
               }
           }
       }
       return postfix.peek();
}

}

//--------------------------------------------------------------------

public class B1Driver {

public static void main(String[] args) {
     
     
Scanner s = new Scanner(System.in);
String format = "";
do {
System.out.print("What format will your formula be in (infix/postfix):");
format = s.nextLine().toLowerCase();
}while(!(format.equals("infix") || format.equals("postfix")));
System.out.print("Enter your formula:");
String formula = s.nextLine().replaceAll(" ", "");//removes whitespace
String infix, postfix;
switch(format) {
case "infix":
infix = formula;
postfix = B1Work.infixToPostfix(infix);
System.out.println("Infix:"+infix);
System.out.println("Postfix:"+postfix);
System.out.println("Answer:"+B1Work.solvePostfix(postfix));
break;
case "postfix":
postfix = formula;
infix = B1Work.postfixToInfix(postfix);
System.out.println("Infix:"+infix);
System.out.println("Postfix:"+postfix);
System.out.println("Answer:"+B1Work.solvePostfix(postfix));
break;
}
}

}

--------------------------------------------------------------------------------------------------------------------------

SEE OUTPUT

254 255 248 public class B1Driver { 249 250 public static void main(String[] args) { 251 252 0.253 Scanner s = new Scanner(Sy

Thanks, PLEASE COMMENT if there is any concern.

Add a comment
Know the answer?
Add Answer to:
Using Java- Write a program that takes an arithmetic expression in an infix form, converts it...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a java program for the following: Your program reads an infix expression represented by a...

    Write a java program for the following: Your program reads an infix expression represented by a string S from the standard input (the keyboard). Then your program converts the infix expression into a postfix expression P using the algorithm. Next, your program evaluates the postfix expression P to produce a single result R. At last, your program displays the original infix expression S, the corresponding postfix expression P and the final result R on the standard output ( the screen...

  • C++ Write a program that takes an infix expression as an input and produces a postfix...

    C++ Write a program that takes an infix expression as an input and produces a postfix expression. Use stack to convert an infix expression into postfix expression. Include a function that evaluates a postfix expression.

  • In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an...

    In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers For Example: Infix expression (6 + 2) * 5 - 8 / 4 to a postfix expression is  62+5*84/- The program should read the expression into character array infix and use the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation;...

    EVALUATING GENERAL INFIX EXPRESSIONS INTRODUCTION The notation in which we usually write arithmetic expressions is called infix notation; in it, operators are written between their operands: X + Y. Such expressions can be ambiguous; do we add or multiply first in the expression 5 + 3 * 2? Parentheses and rules of precedence and association clarify such ambiguities: multiplication and division take precedence over addition and subtraction, and operators associate from left to right. This project implements and exercises a stack-based algorithm that evaluates...

  • We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are...

    We as humans write math expression in infix notation, e.g. 5 + 2 (the operators are written in-between the operands). In a computer’s language, however, it is preferred to have the operators on the right side of the operands, i.e. 5 2 +. For more complex expressions that include parenthesis and multiple operators, a compiler has to convert the expression into postfix first and then evaluate the resulting postfix. Write a program that takes an “infix” expression as input, uses...

  • Write a java program to convert and print an infix expression to postfix expression. You can...

    Write a java program to convert and print an infix expression to postfix expression. You can use Java stack methods. (Must read input from System.in) Your main method should be as follow: public static void main(String args[]) { intopost p = new intopost (); String iexp, pexp; //infix postfix expression             try{ Scanner inf = new Scanner (System.in);                     // Read input from KB/ File while(inf.hasNext()){ // read next infix expression                                 iexp = inf.next(); // Assume method name to convert infix...

  • (In Java) you will be creating a GUI for your calculator that evaluates the postfix expression. I...

    (In Java) you will be creating a GUI for your calculator that evaluates the postfix expression. I have already created the postfix class that converts the expression from infix to postfix. Here's the postFix class and its stack class (https://paste.ofcode.org/bkwPyCMEBASXQL4pR2ym43) ---> PostFix class (https://paste.ofcode.org/WsEHHugXB38aziWRrp829n)--------> Stack class Your calculator should have: Text field for the postfix expression Text field for the result Two buttons: Evaluate and Clear You can start with the code written below and improvise to work with this...

  • Complete the following java program in which infix expressions should be converted to postfix expressions /**...

    Complete the following java program in which infix expressions should be converted to postfix expressions /** * An algebraic expression class that has operations such as conversion from infix * expression to postfix expression, * and evaluation of a postfix expression */ public class Expression { /** * The infix of this expression */ private String infix; /** * Constructs an expression using an infix. */ public Expression(String infix){ this.infix = infix; } /** * Converts an infix expression into...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT