Question

In: Computer Science

Java. Complete the methods for infixToPostfix, postfixToInfix, solvePostfix. import java.util.Stack; public class B1Work {    /*...

Java. Complete the methods for infixToPostfix, postfixToInfix, solvePostfix.

import java.util.Stack;

public class B1Work {
   /*
   * Grading:
   * Correctly converts infix to postfix - 3pts
   */
   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*-
       */
       return null;
   }
   /*
   * Grading:
   * Correctly converts postfix to infix - 2pts
   */
   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
       */
       return null;
   }
   /*
   * Grading:
   * Correctly solves postfix formulas with +-/* - 1pt
   */
   public static double solvePostfix(String postfix) {
       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
       */
       return 0;
   }
}

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

import java.util.Scanner;

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;
       }
   }

}

Solutions

Expert Solution

import java.util.Stack;
public class B1Work {
/*
* Grading:
* Correctly converts infix to postfix - 3pts
*/
  
   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 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;
}
/*
* Grading:
* Correctly converts postfix to infix - 2pts
*/


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();
}
/*
* Grading:
* Correctly solves postfix formulas with +-/* - 1pt
*/
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();
}
}

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

import java.util.Scanner;
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




Thanks, PLEASE COMMENT if there is any concern.

Stack<String> stack = new Stack<String>(); for (int i = 0; i < postfix.length(); i++) 116 117 118 119 120 121 122 123 124 if (isCharacter postfix.charAt(i))) stack.push(postfix.charAt(i) + ""); else 125 126 127 128 129 130 String operator1 = stack.peek(); stack.pop(); String operator2 = stack.peek(); stack.pop(); stack.push("(" + operator2 + postfix.charAt(i) + operator1 + ")"); 131 132 133 return stack.peek(); 134 1352 /* 136 * Grading: 137 * Correctly solves postfix formulas with +-/* - 1pt e Console X X X Ex : 9 <terminated> B1 Driver [Java Application] /Library/Java/JavaVirtual Machines/jdk1.8.0_202.jdk/Contents/Home/bin/ja What format will your formula be in (infix/postfix): infix Enter your formula:(1+(2-3)) Infix:(1+(2-3)) Postfix: 123-+ Answer:0.0


Related Solutions

import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        } System.out.println(""+getAvg(new_stack));    }     public static int getAvg(Stack s) {        //TODO: Find the average of the elements in the...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
Stack2540Array   import java .io .*; import java . util .*; public class Stack2540Array { int CAPACITY...
Stack2540Array   import java .io .*; import java . util .*; public class Stack2540Array { int CAPACITY = 128; int top ; String [] stack ; public Stack2540Array () { stack = new String [ CAPACITY ]; top = -1; } 1 public int size () { return top + 1; } public boolean isEmpty () { return (top == -1); } public String top () { if ( top == -1) return null ; return stack [ top ]; }...
Please provide the missng code(parts) for the given code in java. ASAP. import java.util.Stack; class StackQueue<T>...
Please provide the missng code(parts) for the given code in java. ASAP. import java.util.Stack; class StackQueue<T> implements Queue<T>{ private Stack<T> inStack; private Stack<T> outStack; private int size; public StackQueue(){ inStack = new Stack<T> (); outStack = PART(a); size = 0; } public int size(){ return size; } public boolean isEmpty(){ return size==0; } public T first(){ if (size == 0) return null;; if (outStack.empty()) while (!inStack.empty()) outStack.push(inStack.pop()); return PART(b); //return the element at the top of the outStack without removing...
Please convert this java program to a program with methods please. import java.io.*; import java.util.*; public...
Please convert this java program to a program with methods please. import java.io.*; import java.util.*; public class Number{ public static void main(String[] args) {    Scanner scan = new Scanner(System.in); System.out.println("Enter 20 integers ranging from -999 to 999 : "); //print statement int[] array = new int[20]; //array of size 20 for(int i=0;i<20;i++){ array[i] = scan.nextInt(); //user input if(array[i]<-999 || array[i]>999){ //check if value is inside the range System.out.println("Please enter a number between -999 to 999"); i--; } } //...
Java: Complete the methods marked TODO. Will rate your answer! -------------------------------------------------------------------------------------------------- package search; import java.util.ArrayList; import...
Java: Complete the methods marked TODO. Will rate your answer! -------------------------------------------------------------------------------------------------- package search; import java.util.ArrayList; import java.util.List; /** * An abstraction over the idea of a search. * * @author liberato * * @param <T> : generic type. */ public abstract class Searcher<T> { protected final SearchProblem<T> searchProblem; protected final List<T> visited; protected List<T> solution; /**    * Instantiates a searcher.    *    * @param searchProblem    *            the search problem for which this searcher will find and   ...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution {...
Convert this java code from hashmap into arraylist. import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); HashMap labs = new HashMap(); while (true) { System.out.println("Choose operation : "); System.out.println("1. Create a Lab"); System.out.println("2. Modify a Lab"); System.out.println("3. Delete a Lab"); System.out.println("4. Assign a pc to a Lab"); System.out.println("5. Remove a pc from a Lab"); System.out.println("6. Quit"); int choice = sc.nextInt(); String name=sc.nextLine(); switch (choice) { case 1:...
import java.util.Stack; import java.util.ArrayList; import java.util.Scanner; class TreeNode{ int data; ArrayList<TreeNode> children = new ArrayList<>(); TreeNode...
import java.util.Stack; import java.util.ArrayList; import java.util.Scanner; class TreeNode{ int data; ArrayList<TreeNode> children = new ArrayList<>(); TreeNode parent = null;    public TreeNode(int d){ data = d; }    public TreeNode addChild(int d){ TreeNode n = new TreeNode(d); n.setParent(this); children.add(n); return n; }    public ArrayList<TreeNode> getChildren(){ return children; }    public void setParent(TreeNode p){ parent = p; }    public TreeNode getParent(){ return parent; } } class Main { public static void main(String[] args)    {        Scanner scan...
import java.util.Stack; import java.util.ArrayList; import java.util.Scanner; class TreeNode{ int data; ArrayList<TreeNode> children = new ArrayList<>(); TreeNode...
import java.util.Stack; import java.util.ArrayList; import java.util.Scanner; class TreeNode{ int data; ArrayList<TreeNode> children = new ArrayList<>(); TreeNode parent = null;    public TreeNode(int d){ data = d; }    public TreeNode addChild(int d){ TreeNode n = new TreeNode(d); n.setParent(this); children.add(n); return n; }    public ArrayList<TreeNode> getChildren(){ return children; }    public void setParent(TreeNode p){ parent = p; }    public TreeNode getParent(){ return parent; } } class Main { public static void main(String[] args)    {        Scanner scan...
import java.util.Stack; import java.util.ArrayList; import java.util.Scanner; class TreeNode{ int data; ArrayList<TreeNode> children = new ArrayList<>(); TreeNode...
import java.util.Stack; import java.util.ArrayList; import java.util.Scanner; class TreeNode{ int data; ArrayList<TreeNode> children = new ArrayList<>(); TreeNode parent = null;    public TreeNode(int d){ data = d; }    public TreeNode addChild(int d){ TreeNode n = new TreeNode(d); n.setParent(this); children.add(n); return n; }    public ArrayList<TreeNode> getChildren(){ return children; }    public void setParent(TreeNode p){ parent = p; }    public TreeNode getParent(){ return parent; } } class Main { public static void main(String[] args)    {        Scanner scan...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT