Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Partl: Binary Print Write a recursive method that prints the binary form of a gi

ID: 3913010 • Letter: P

Question

Partl: Binary Print Write a recursive method that prints the binary form of a given non-negative integer, with the following specification: public class NPrintf public static void binaryPrint (int n) t I/ your implementation The method prints the value of n as a BINARY number. If n is zero, then a single zero is printed; otherwise no leading zeros are printed in the output. Examples: n-0 Output:0 n-4 Output:100 n-27 Output:11011 Hint: How to convert an int to its binary form? A very intuitive way is to divide the number by 2 in each recursion. In each recursive call, you print either 0 (unless it is a leading zero) if 2 divides n, or'' otherwise. Part2: Evaluate Arithmetic Expressions Requirements 1. Implement a concrete ArrayStack class that extends the Stack interface as we discussed in the class (any other different Stack class implementation, even if it is i yourself, will not receive any credit). 2. Write a method that evaluates an arithmatic expression, which is given by a string. public class Evaluate t public static int expression (String str)( // return the value 3. Your implementation is required to use the Stack interface we discussed in the class. 4. Write a necessary test program to verify the result. For example, 14-3 4+2 5-6 2 (should return 0) You may want to test all possible corner conditions to make sure your implement is inclusive parentheses. examples: 5. Your implementation only considers+ and * operators and does not need to consider 6. Bonus: extra 10 points will be awarded if you implementation supports parentheses. For 14-3* (4+2 (5-6))*2 (should return 2) Submission 1. Each student submits one copy of the source code: NPrint.java, Evaluate java, Stack.java and ArrayStack.java. Please also provide the corresponding test programs.

Explanation / Answer

Nprint:

import java.util.Scanner;
public class Nprint
{
   public static void main(String[] args)
   {
       int dec;
       Scanner sc = new Scanner(System.in);
       System.out.print("Enter decimal number:");
       dec = sc.nextInt();
       if(dec==0)
           System.out.println("Binary number:"+0);
       if(dec>0)
           System.out.println("Binary number:"+binary(dec));
   }
   public static String binary(int dec)
   {
       if(dec > 0)
           return (binary(dec / 2) + "" + dec%2);
       return "";
   }
}

ArrayStack:

import java.util.Scanner;
@SuppressWarnings("unchecked")
class ArrayStack<AnyType> implements StackInterface<AnyType>
{
   private static final int DEFAULT_CAPACITY = 15;
   private int top;       // reference to the top element
   private AnyType[] A;
   public ArrayStack(int initialCapacity)
   {
        A = (AnyType[]) new Object[initialCapacity];
       top = -1;   //stack is empty
   }
   public ArrayStack()
   {
      this(DEFAULT_CAPACITY);
   }
   public boolean isEmpty()
   {
      return top==-1;
   }
   public AnyType peek()
   {
       return A[top];
   }
   public AnyType pop()
   {
      if(top==-1)
       System.out.println("UnderFlow");
      return A[top--];
   }
   public void push(AnyType e)
   {
      if (top == A.length)
          System.out.println("OverFlow");
      A[++top] = e;
   }

   public String toString()
   {
      if(isEmpty()) return "[ ]";
      StringBuffer out = new StringBuffer("[");
      for(int i = 0; i < top; i++)
         out.append(A[i] + ", ");
      out.append(A[top] + "]");
      return out.toString();
   }

   public static void main(String[] args)
   {
      ArrayStack<Integer> s = new ArrayStack<Integer>(6);
       Scanner sc=new Scanner(System.in);
       int choice;
       do
       {
           System.out.println("1.Push 2.Pop 3.Display 4.Exit");
           choice=sc.nextInt();
           if(choice==1)
           {
               System.out.println("Enter Pushing element: ");
               int element=sc.nextInt();
               s.push(element);
           }
           else if(choice==2)
               s.pop();
           else if(choice==3)
               System.out.println(s);
       }while(choice!=4);
   }
}
/**              StackInterface           **/
interface StackInterface<AnyType>
{
   //checks whether stack is empty or not
   public boolean isEmpty();

   //Pop operation
   public AnyType pop();

   //Push onto stock
   public void push(AnyType e);
  
   //Top of the stack
   public AnyType peek();
}


Evaluate Expression:

import java.util.Scanner;
@SuppressWarnings("unchecked")
class ArrayStack<AnyType> implements StackInterface<AnyType>
{
   private static final int DEFAULT_CAPACITY = 15;
   private int top;     // reference to the top element
   private AnyType[] A;

   public ArrayStack(int initialCapacity)
   {
        A = (AnyType[]) new Object[initialCapacity];
       top = -1;   //stack is empty
   }

   public ArrayStack()
   {
      this(DEFAULT_CAPACITY);
   }

   public boolean isEmpty()
   {
      return top==-1;
   }

   public AnyType peek()
   {
       return A[top];
   }

   public AnyType pop()
   {
      if(top==-1)
       System.out.println("UnderFlow");
      return A[top--];
   }
   public void push(AnyType e)
   {
      if (top == A.length)
          System.out.println("OverFlow");
      A[++top] = e;
   }
    public static int evaluate(String tokens)
    {
        //char[] tokens = expression.toCharArray();

         // Stack for numbers: 'operands'
        ArrayStack<Integer> operands = new ArrayStack<Integer>(100);

        // Stack for Operators: 'operators'
        ArrayStack<Character> operators = new ArrayStack<Character>(100);
      
       for (int i = 0; i < tokens.length(); i++)
        {
          
             // if got whitespace
            if (tokens.charAt(i) == ' ')
                continue;

            // if got a number push onto stack
            if (tokens.charAt(i) >= '0' && tokens.charAt(i) <= '9')
            {
                String num="";
                // There may be more than one digits in number
                while (i < tokens.length() && tokens.charAt(i) >= '0' && tokens.charAt(i) <= '9')
               {
                   num=num+tokens.charAt(i);
                   i++;
               }
               i--;
                operands.push(Integer.parseInt(num));
            }
          
            // if got ( push onto operator stack
            else if (tokens.charAt(i) == '(')
                operators.push(tokens.charAt(i));

            // if got ) solve entire expression untill find (
            else if (tokens.charAt(i) == ')')
            {
                while (operators.peek() != '(')
                  operands.push(doOperation(operators.pop(), operands.pop(), operands.pop()));
                operators.pop();
            }

            // Current token is an operator.
            else if (tokens.charAt(i) == '+' || tokens.charAt(i) == '-' ||
                     tokens.charAt(i) == '*' || tokens.charAt(i) == '/')
            {
                // While top of 'operators' has same or greater precedence to current
                // token, which is an operator. Apply operator on top of 'operators'
                // to top two elements in operands stack
                while (!operators.isEmpty() && hasPrecedence(tokens.charAt(i), operators.peek()))
                  operands.push(doOperation(operators.pop(), operands.pop(), operands.pop()));

                // Push current token to 'operators'.
                operators.push(tokens.charAt(i));
            }
          
        }
          
        //Expression is over then do remaining operation with respect to operators
        while (!operators.isEmpty())
            operands.push(doOperation(operators.pop(), operands.pop(), operands.pop()));

        // Top of 'operands' contains result, return it
        return operands.pop();
    }

    // Returns true if 'op2' has higher or same precedence as 'op1',
    // otherwise returns false.
    public static boolean hasPrecedence(char op1, char op2)
    {
        if (op2 == '(' || op2 == ')')
            return false;
        if ((op1 == '*' ) && (op2 == '+' || op2 == '-'))
            return false;
        else
            return true;
    }

    // A utility method to apply an operator 'op' on operands 'a'
    // and 'b'. Return the result.
    public static int doOperation(char op, int b, int a)
    {
        switch (op)
        {
           case '+':
               return a + b;
           case '-':
               return a - b;
           case '*':
               return a * b;
        }
        return 0;
    }

    // Driver method to test above methods
    public static void main(String[] args)
    {
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter Expression to evaluate: ");
       String expression= sc.next();
        System.out.println(evaluate(expression));
    }
}
interface StackInterface<AnyType>
{
   //checks whether stack is empty or not
   public boolean isEmpty();

   //Pop operation
   public AnyType pop();

   //Push onto stock
   public void push(AnyType e);
  
   //Top of the stack
   public AnyType peek();
}