Question

Assignment4: Evaluate Arithmetic Expressions. Requirements: Implement a concrete ArrayStack class that extends the IStack interface as...

Assignment4: Evaluate Arithmetic Expressions.


Requirements:

  1. Implement a concrete ArrayStack class that extends the IStack interface as we discussed in the class (any other different Stack class implementation, even if it is implemented by yourself, will not receive any credit).
  2. Write a test class called Evaluate and a method that evaluates an arithmatic expression, which is given by a string.
import java.util.Scanner;

public class Evaluate {

  public static void main(String[] args) }
    // your implementation
    // obtain user's input from keyboard
    // invoke method expression() to get the result and print it out
  }

  public static int expression(String str) {
        // return the value
  }
}

public interface IStack {

abstract public int size();

//returns size of stack
   abstract public Object top();

//returns top of stack
   abstract public Object pop();

//removes top of stack and returns value
   abstract public void push(Object x) throws FullStackException;

//inserts data object to top of stack
   abstract public boolean isEmpty();

//returns true or false if stack is empty

}

  1. Your implementation is required to use the IStack interface we discussed in the class.
  2. provide a necessary test case to verify the result. For example,
    14-3*4+2*5-6*2 (should return 0)
    
    In another example,
    14-3*(4+2*(5-6))*2 (should return 2) 
    
    You may want to test all possible corner conditions to make sure your implement is inclusive.
  3. Your implementation only considers +, - and * operators, as well as the parentheses (), and does not need to consider other operators and brackets. In particular, your code should not work with division operator "/".

Grading Criteria:

  • Please make sure your program compiles, otherwise your submission will not be graded and you will receive zero.
  • Point deduction rule:
    1. Compile warning: 3 points each.
    2. Minor error: such as not meeting the assignment input/output requirement, 5 points each.
    3. Major error: examples include, infinite loop, runtime errors, any runtime exception, 15 points each.
    4. Any code not compliant to the assignment requirement (e.g., not using IStack interface or ever using generic programming) will not be graded and you will receve zero.
    5. 20 point penalty if your program works with division operator "/".
  • (40%) Correct implementation of IStack.java, ArrayStack.java and StackFullException.java.
  • (40%) Correct implementation of Evaluate class with the expression method that correctly evaluates the expression with +, - and * operators.
  • (10%) The above expression method supports the parentheses ().
  • (10%) Correct README file (with the required contents).
0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE:

// NPrint.java

import java.util.Scanner;

public class NPrint

{

   //main method

    public static void main(String[] args)

    {

        int decimalvalue;

        Scanner sc1 = new Scanner(System.in);

        System.out.print("Enter decimal number:");

        decimalvalue = sc1.nextInt();

        if(decimalvalue==0)

            System.out.println("Binary number:"+0);

        if(decimalvalue>0)

            System.out.println("Binary number:"+binaryvalue(decimalvalue));

    }

    public static String binaryvalue(int decimalvalue)

    {

        if(decimalvalue > 0)

            return (binaryvalue(decimalvalue / 2) + "" + decimalvalue%2);

        return "";

    }

}

part 2:

// ArrayStack.java

import java.util.Scanner;

@SuppressWarnings("unchecked")

//stack interface

class ArrayStack<AnyType> implements Stack_Interface<AnyType>

{

    private static final int defaultvalue = 15;

    private int topvalue;    

    private AnyType[] A;

    public ArrayStack(int initial_Capacity)

    {

         A = (AnyType[]) new Object[initial_Capacity];

        topvalue = -1;

    }

    public ArrayStack()

    {

       this(defaultvalue);

    }

    public boolean is_Empty()

    {

       return topvalue==-1;

    }

    public AnyType peekvalue()

    {

        return A[topvalue];

    }

    public AnyType popvalue()

    {

       if(topvalue==-1)

        System.out.println("UnderFlow");

       return A[topvalue--];

    }

    public void pushvalue(AnyType e)

    {

       if (topvalue == A.length)

           System.out.println("OverFlow");

       A[++topvalue] = e;

    }

     public static int evaluateoperation(String tok)

     {

       

         ArrayStack<Integer> opr = new ArrayStack<Integer>(100);

         ArrayStack<Character> opvalue = new ArrayStack<Character>(100);

      

        for (int i = 0; i < tok.length(); i++)

         {

          

           

             if (tok.charAt(i) == ' ')

                 continue;

            

             if (tok.charAt(i) >= '0' && tok.charAt(i) <= '9')

             {

                 String numvalue="";

                

             

   while (i < tok.length() && tok.charAt(i) >= '0' && tok.charAt(i) <= '9')

                {

                    numvalue=numvalue+tok.charAt(i);

                    i++;

                }

                i--;

                 opr.pushvalue(Integer.parseInt(numvalue));

             }

          

            

             else if (tok.charAt(i) == '(')

                 opvalue.pushvalue(tok.charAt(i));

             

             else if (tok.charAt(i) == ')')

             {

                 while (opvalue.peekvalue() != '(')

                   opr.pushvalue(do_Operation(opvalue.popvalue(), opr.popvalue(), opr.popvalue()));

                 opvalue.popvalue();

             }

        

             else if (tok.charAt(i) == '+' || tok.charAt(i) == '-' ||

                      tok.charAt(i) == '*' || tok.charAt(i) == '/')

             {

               

                 while (!opvalue.is_Empty() && has_Precedence(tok.charAt(i), opvalue.peekvalue()))

                   opr.pushvalue(do_Operation(opvalue.popvalue(), opr.popvalue(), opr.popvalue()));

                

                 opvalue.pushvalue(tok.charAt(i));

             }

          

         }

           

        

         while (!opvalue.is_Empty())

             opr.pushvalue(do_Operation(opvalue.popvalue(), opr.popvalue(), opr.popvalue()));

       

         return opr.popvalue();

     }

    

     public static boolean has_Precedence(char op1val, char op2val)

     {

         if (op2val == '(' || op2val == ')')

             return false;

         if ((op1val == '*' ) && (op2val == '+' || op2val == '-'))

             return false;

         else

             return true;

     }

    

     public static int do_Operation(char op1, int b1, int a1)

     {

         switch (op1)

         {

            case '+':

                return a1 + b1;

            case '-':

                return a1 - b1;

            case '*':

                return a1 * b1;

         }

         return 0;

     }

    

     public static void main(String[] args)

     {

        Scanner sc1=new Scanner(System.in);

        System.out.println("Enter Expression to evaluateoperation: ");

        String expression= sc1.next();

         System.out.println(evaluateoperation(expression));

     }

}

   

// Stack_Interface.java

interface Stack_Interface<AnyType>

{

  

   public boolean is_Empty();

   public AnyType popvalue() ;

   public AnyType peekvalue() ;

   public void pushvalue(AnyType e) ;

}

Add a comment
Know the answer?
Add Answer to:
Assignment4: Evaluate Arithmetic Expressions. Requirements: Implement a concrete ArrayStack class that extends the IStack interface as...
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
  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression...

    C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression convertor Stacks A stack is an abstract data type which uses a sequential container and limits access to that container to one end. You may enter or remove from the container, but only at one end. Using the Linked List data structure from your last homework assignment, implement a Stack of type string. The Stack should only have one data member: the Linked List....

  • 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...

  • In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack...

    In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack are of generic DataType. This means use should use templating and your Node class. Structure  The stack data items are linearly ordered from the most recently added (the top) to the least recently added (the bottom). This is a LIFO scheme. Data items are inserted onto (pushed) and removed from (popped) the top of the stack.  Operations  Constructor. Creates an empty stack.  Copy constructor....

  • For this project you will implement a simple calculator. Your calculator is going to parse infix...

    For this project you will implement a simple calculator. Your calculator is going to parse infix algebraic expressions, create the corresponding postfix expressions and then evaluate the postfix expressions. The operators it recognizes are: +, -, * and /. The operands are integers. Your program will either evaluate individual expressions or read from an input file that contains a sequence of infix expressions (one expression per line). When reading from an input file, the output will consist of two files:...

  • In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> {...

    In Java. What would the methods of this class look like? StackADT.java public interface StackADT<T> { /** Adds one element to the top of this stack. * @param element element to be pushed onto stack */ public void push (T element);    /** Removes and returns the top element from this stack. * @return T element removed from the top of the stack */ public T pop(); /** Returns without removing the top element of this stack. * @return T...

  • The code below accepts and evaluates an integer expression with the following operators: +, _, *,...

    The code below accepts and evaluates an integer expression with the following operators: +, _, *, and /. Your task is to modify it to include the % remainder operator that has the same precedence as * and /. No need to rewrite the entire program, just insert the needed statements. import java.util.Stack; public class EvaluateExpression { public static void main(String[] args) {     // Check number of arguments passed     if (args.length != 1) {       System.out.println(         "Usage:...

  • Need Help ASAP!! Below is my code and i am getting error in (public interface stack)...

    Need Help ASAP!! Below is my code and i am getting error in (public interface stack) and in StackImplementation class. Please help me fix it. Please provide a solution so i can fix the error. thank you.... package mazeGame; import java.io.*; import java.util.*; public class mazeGame {    static String[][]maze;    public static void main(String[] args)    {    maze=new String[30][30];    maze=fillArray("mazefile.txt");    }    public static String[][]fillArray(String file)    {    maze = new String[30][30];       try{...

  • I need help with the Implementation of an Ordered List (Template Files) public interface Ordered...

    I need help with the Implementation of an Ordered List (Template Files) public interface OrderedStructure { public abstract int size(); public abstract boolean add( Comparable obj ) throws IllegalArgumentException; public abstract Object get( int pos ) throws IndexOutOfBoundsException; public abstract void remove( int pos ) throws IndexOutOfBoundsException; public abstract void merge( OrderedList other ); } import java.util.NoSuchElementException; public class OrderedList implements OrderedStructure { // Implementation of the doubly linked nodes (nested-class) private static class Node { private Comparable value; private...

  • Evaluateeg EvaluateInFix.java: import java.util.Stack; import java.util.Scanner; public class EvaluateInfix {    public static void main(String[] args)...

    Evaluateeg EvaluateInFix.java: import java.util.Stack; import java.util.Scanner; public class EvaluateInfix {    public static void main(String[] args)    {    Scanner keyboard = new Scanner(System.in); System.out.println("This program an inFix Expression: "); System.out.print("Enter an inFix Expression that you want to evaluate (or enter ! to exit): "); String aString = keyboard.nextLine();    while (!aString.equals("!")) {    System.out.println (evaluateinFix(aString));    System.out.print("Enter an inFix Expression that you want to evaluate (or enter ! to exit): ");    aString = keyboard.nextLine(); } // end while...

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