Question

*JAVA* Can somebody take a look at my current challenge? I need to throw a different...

*JAVA*

Can somebody take a look at my current challenge?

I need to throw a different exception when

a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax"

The code is as follows.

Stack class:

public class ArrayStack<E> {

   private int top, size;
   private E arrS[];
   private static final int MAX_STACK_SIZE = 10;

   public ArrayStack() {
       this.arrS = (E[]) new Object[MAX_STACK_SIZE];
       this.top = size;
       this.size = 0;
   }

   public void push(E value) {
       if (isFull() == true) {
           throw new ArrayIndexOutOfBoundsException("Stack is Full");
       } else
           this.arrS[this.size++] = value;

   }

   public E pop() {
       if (isEmpty() == true) {
           throw new ArrayIndexOutOfBoundsException("Stack is Empty");
       }
       return this.arrS[--this.size];
   }

   public boolean isFull() {
       return (this.size == MAX_STACK_SIZE) ? true : false;

   }

   public boolean isEmpty() {
       return (this.size == 0) ? true : false;

   }

   public int length() {
       return this.size;
   }

   public E topValue() {
       if (isEmpty() == true) {
           throw new IllegalArgumentException();
       }
       return this.arrS[this.size - 1];
   }

   public void clear() {
       this.size = 0;

   }

   public String show() {

       StringBuilder sb = new StringBuilder();
       sb.append(" ");
       for (int i = 0; i < this.size; i++) {
           sb.append(this.arrS[i]);
           sb.append(" ");

       }
       sb.append("");
       return sb.toString();

   }

}

Main driver:


import java.util.Scanner;

public class a3main {

   public static void main(String[] args) {
       int count = 0;

       Scanner scan = new Scanner(System.in);

       do {
           System.out.println("Enter an algebraic or arithmetic expression: ");

           String arg = scan.nextLine();

           ArrayStack<Character> stack = new ArrayStack<Character>();
           boolean flag = true;
           for (int i = 0; i < arg.length(); i++) {
               count++;
               char current = arg.charAt(i);

               if (current == '{' || current == '[' || current == '(') {
                   try {
                       stack.push(current);
                   } catch (Exception e) {
                       System.out.println("Excessive parenthesis combinations" + "\n");
                       flag = false;
                       break;

                   }
               }

               if ((current == '}' || current == ')' || current == ']')) {
                   if (stack.isEmpty() == true) {
                       System.out.println(
                               "Encountered error on the right of the expression: Missing left parenthesis" + "\n");
                       flag = false;
                       break;
                   }
                   char last = stack.topValue();
                   if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
                       stack.pop();
                   else {

                       flag = false;

                       System.out.println("Mismatch between right and left closing statements " + "\n");
                       break;
                   }
               }

           }
           if (flag) {
               if (stack.isEmpty() == true) {
                   System.out.println("Correct parenthesis combinations: match" + "\n");
               } else {
                   System.out.println(
                           "Encountered error on the left of the expression: Missing right parenthesis" + "\n");
               }
           }
       } while (count != 0);
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hello,

Here is the code, I have put all my comments in the code. Also, I have enclosed the screenshot of result for your reference.

All the very best !!!

import java.util.Scanner;

public class a3main extends Exception{ // You need to extend Exception class to throw your own exception

    public a3main (String s){

        super(s); // Calling the constructor of Exception class
    }

    public static void main(String[] args) {
        int count = 0;

        Scanner scan = new Scanner(System.in);
        boolean exception = false; // I have a flag added to continue after the exception
        do {
            System.out.println("Enter an algebraic or arithmetic expression: ");

            String arg = scan.nextLine();

            ArrayStack<Character> stack = new ArrayStack<Character>();
            boolean flag = true;
            
            try{ // Introduced a try catch block to make sure expression doesn't contain )(, in case then throw the exception
                
                if (arg.contains(")(")){
                    throw new a3main("Correct number of parenthesis but incorrect syntax\n"); // Here is the text you are looking for
                }
                
            } catch (Exception e) { // Catch the exception thrown, set the exception flag to true 
                
                System.out.println(e.getMessage());
                exception = true;
            }
            if (exception==true){ // if exception, then flag exception is set and simply continue.
                count++;
                continue;
            }

            for (int i = 0; i < arg.length(); i++) { // Rest all is your code untouched
                count++;

                char current = arg.charAt(i);

                if (current == '{' || current == '[' || current == '(') {
                    try {
                        stack.push(current);
                    } catch (Exception e) {
                        System.out.println("Excessive parenthesis combinations" + "\n");
                        flag = false;
                        break;

                    }
                }

                if ((current == '}' || current == ')' || current == ']')) {
                    if (stack.isEmpty() == true) {
                        System.out.println(
                                "Encountered error on the right of the expression: Missing left parenthesis" + "\n");
                        flag = false;
                        break;
                    }
                    char last = stack.topValue();
                    if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
                        stack.pop();
                    else {

                        flag = false;

                        System.out.println("Mismatch between right and left closing statements " + "\n");
                        break;
                    }
                }

            }
            if (flag) {
                if (stack.isEmpty() == true) {
                    System.out.println("Correct parenthesis combinations: match" + "\n");
                } else {
                    System.out.println(
                            "Encountered error on the left of the expression: Missing right parenthesis" + "\n");
                }
            }
        } while (count != 0);
    }
}
Add a comment
Know the answer?
Add Answer to:
*JAVA* Can somebody take a look at my current challenge? I need to throw a different...
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 Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity...

    JAVA Implement a MyQueue class which implements a queue using two stacks. private int maxCapacity = 4; private Stack stack1; private Stack stack2; Note: You can use library Stack but you are not allowed to use library Queue and any of its methods Your Queue should not accept null or empty String or space as an input You need to implement the following methods using two stacks (stack1 & stack2) and also you can add more methods as well: public...

  • 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 have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT w...

    I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT with the implementation of your choice (Array or Link), it should not make a difference 2.Read two “integer” numbers from the user. Hint: You don’t need to use an int type when you read, it may be easier to parse the input...

  • What is wrong with my code, when I pass in 4 It will not run, without...

    What is wrong with my code, when I pass in 4 It will not run, without the 4 it will run, but throw and error. I am getting the error   required: no arguments found: int reason: actual and formal argument lists differ in length where T is a type-variable: T extends Object declared in class LinkedDropOutStack public class Help { /** * Program entry point for drop-out stack testing. * @param args Argument list. */ public static void main(String[] args)...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

  • I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and...

    I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and size using below pseudo code. I need two classes with stack pseudo code implementation and the main method to demonstrate the correct working of each operation. pseudo code StackADT (using raw array) class StackADT { int top int items[] int max StackADT(int n) Initialize array to n capacity top = 0 max = n boolean isEmpty() if array has no elements return true else...

  • Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,In...

    Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix)    {        LinkedStack stack2 = new LinkedStack();        int val1;        int val2;        int result;        for(int i = 0; i < postFix.length(); i++)        {            char m = postFix.charAt(i);            if(Character.isDigit(m))            {                stack2.push(m);            }            else            {               ...

  • java create java program that make stack with LinkedList and stack is implement iterator. When stack’s iterator call next(), it pop its data. here is the example of output //by user 5 1 2 3 4 5 //then...

    java create java program that make stack with LinkedList and stack is implement iterator. When stack’s iterator call next(), it pop its data. here is the example of output //by user 5 1 2 3 4 5 //then output comes like this 5 4 3 2 1 Stack is empty. here is the code that i'm going to use class Stack<T> implements Iterator<T> {    LinkedList<T> list;       public Stack() {        list = new LinkedList<T>();    }       public boolean isEmpty() {        return list.isEmpty();   ...

  • My Question is: I have to modify this program, even a small modification is fine. Can...

    My Question is: I have to modify this program, even a small modification is fine. Can anyone give any suggestion and solution? Thanks in Advanced. import java.util.*; class arrayQueue { protected int Queue[]; protected int front, rear, size, len; public arrayQueue(int n) { size = n; len = 0; Queue = new int[size]; front = -1; rear = -1; } public boolean isEmpty() { return front == -1; } public boolean isFull() { return front == 0 && rear ==size...

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