Question

In: Computer Science

JAVA: Use existing Java Stack class to solve the "Balancing Symbols" problem. The symbols are (),...

JAVA:

Use existing Java Stack class to solve the "Balancing Symbols" problem. The symbols are (), [], and {}, and each opening symbol must have a corresponding closing symbol as well as in correct order. Ignore operands and arithmetic operators since they are not relevant to our problem. You can assume each token is separated by spaces. For example:

  • { ( a + b ) * c1 } – valid

  • { ( a + b ) * c1 ] – invalid

  • ( ( a + b ) * c1 } / 15 ) – invalid

    Outline a solution to handle an expression like {(a+25 )*c1}. Notice that spaces are now optional.

    Implement a Queue ADT using a circular array with 5 string elements. Create a Queue object and try various operations below.

    Queue myQueue; // Queue myQueue = new Queue(); in JavamyQueue.enqueue(“CPS 123”);
    myQueue.enqueue(“CPS 223”);
    myQueue.enqueue(“CPS 323”);

    myQueue.dequeue();
    myQueue.enqueue(“CPS 113”);
    myQueue.enqueue(“CPS 153”);
    string course = myQueue.front(); // course should be CPS 223 size = myQueue.size(); // size should be 4

           // output course and size
    

Solutions

Expert Solution

Please find the answer below, all the details are mentioned in the comments.

BalancingSymbols.java
import java.util.Scanner;
import java.util.Stack;

public class BalancingSymbols {
    public static void main(String[] args) {
        //scanner to take the input
        Scanner sc = new Scanner(System.in);
        String input;
        //get the string from user
        System.out.print("Enter the expression: ");
        input = sc.nextLine();

        //call the method to check balance parentheses
        if (checkBalancedSymbols(input)) {
            System.out.println(input + " - valid");
        } else {
            System.out.println(input + " - invalid");
        }
    }

    //method to check balance parentheses
    private static boolean checkBalancedSymbols(String input) {
        //create a stack to hold the character values
        Stack<Character> stack = new Stack<Character>();

        //traverse through the input string
        for (int i = 0; i < input.length(); i++) {
            //get the ith character at a time
            char c = input.charAt(i);
            //if it's opening parentheses then push it to the stack
            if (c == '[' || c == '(' || c == '{') {
                stack.push(c);
            }
            //else if it's closing parentheses then check if stack is not empty and check if the corresponding opening
            // parentheses exist on the top of the stack if not then return false else continue to check
            else if (c == ']') {
                if (stack.isEmpty() || stack.pop() != '[') {
                    return false;
                }
            } else if (c == ')') {
                if (stack.isEmpty() || stack.pop() != '(') {
                    return false;
                }
            } else if (c == '}') {
                if (stack.isEmpty() || stack.pop() != '{') {
                    return false;
                }
            }

        }
        //in the end stack should be empty to be balanced string so will return the status of the
        //stack at that time
        return stack.isEmpty();
    }
}

Output:

Without space character

Queue Implementation:

//implementation of circular queue
class Queue<E> {

    //current size of the queue
    private int currentSize;
    //elements of the queue
    private E[] elements;
    //max size of the queue
    private int maxSize;

    //rear of the queue
    private int rear;
    //front of the queue
    private int front;

    //constructor
    public Queue() {
        //assign max size
        this.maxSize = 5;
        //allocate the memory to hold elements
        elements = (E[]) new Object[this.maxSize];
        //current size to 0
        currentSize = 0;
        //front and rear to -1
        front = -1;
        rear = -1;
    }

    /**
     * Enqueue elements to queue.
     */
    public void enqueue(E item) {
        if (isFull()) {
            System.out.println("Circular Queue is full. Element cannot be added");
        } else {
            rear = (rear + 1) % elements.length;
            elements[rear] = item;
            currentSize++;

            if (front == -1) {
                front = rear;
            }
        }
    }

    /**
     * Dequeue element from Front.
     */
    public E dequeue() {
        E deQueuedElement = null;
        if (isEmpty()) {
            System.out.println("Circular Queue is empty. Element cannot be retrieved");
        } else {
            deQueuedElement = elements[front];
            elements[front] = null;
            front = (front + 1) % elements.length;
            currentSize--;
        }
        return deQueuedElement;
    }

    /**
     * Check if queue is full.
     */
    public boolean isFull() {
        return (currentSize == elements.length);
    }

    /**
     * Check if Queue is empty.
     */
    public boolean isEmpty() {
        return (currentSize == 0);
    }

    /**
     * return the front element and null if empty
     * @return
     */
    public E front(){
        return elements[front];
    }

    /**
     * return the size of the queue
     * @return
     */
    public int size() {
        return currentSize;
    }
}
QueueTest.java
public class QueueTest {
    public static void main(String[] args) {
        Queue<String> myQueue = new Queue(); // Queue myQueue = new Queue(); in Java
        myQueue.enqueue("CPS 123");
        myQueue.enqueue("CPS 223");
        myQueue.enqueue("CPS 323");

        myQueue.dequeue();
        myQueue.enqueue("CPS 113");
        myQueue.enqueue("CPS 153");
        String course = myQueue.front(); // course should be CPS 223 size = myQueue.size(); // size should be 4

        System.out.println("Front: " + course);
        System.out.println("Size: " + myQueue.size());
    }
}

Output:

Please let us know in the comments if you face any problems.

pere de representare la strada 9-15lban)Java" "C:\Program Files\Java\jdk1.8.0_151\bin\java" .. Enter the expression: { (a + b) * cl } { ( a + b) * cl } - valid

"C:\Program Files\Java\jdk1.8.0_151\bin\java" ... Enter the expression: { (a + b) * cl ] { ( a + b) * cl ] - invalid

"C:\Program Files\Java \jdk1.8.0_151\bin\java" ... Enter the expression: ( a + b) * cl } / 15 ) (( a + b ) * cl } / 15 ) - invalid

"C:\Program Files\Java \jdk1.8.0_151\bin\java" ... Enter the expression: {(a+25 ) *c1} {(a+25 ) *cl} - valid


Related Solutions

Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class Stack{ public Stack(){ // use LinkedList class } public void push(int item){ // push item to stack } public int pop(){ // remove & return top item in Stack } public int peek(){ // return top item in Stack without removing it } public boolean isEmpty(){ // return true if the Stack is empty, otherwise false } public int getElementCount(){ // return current number...
Java Generics (Javas built-in Stack) What are the problems?    class genStck {         Stack stk...
Java Generics (Javas built-in Stack) What are the problems?    class genStck {         Stack stk = new Stack ();         public void push(E obj) {                         push(E);                 }         public E pop() {        Object obj = pop();         }    }        class Output {         public static void main(String args[]) {             genStck <> gs = new genStck ();             push(36);             System.out.println(pop());         }    }
Using existing Stack Java Collection Framework, write Java Code segment to do the following.   You may...
Using existing Stack Java Collection Framework, write Java Code segment to do the following.   You may write this in jGrasp Create a Stack of String called, myStacks Read input from keyboard, 10 names and then add to myStacks As you remove each name out, you will print the name in uppercase along with a number of characters the name has in parenthesis. (one name per line).   e.g.     Kennedy (7) Using existing Stack Java Collection Framework, write Java Code segment to...
0. Introduction. In this assignment you will implement a stack as a Java class, using a...
0. Introduction. In this assignment you will implement a stack as a Java class, using a linked list of nodes. Unlike the stack discussed in the lectures, however, your stack will be designed to efficiently handle repeated pushes of the same element. This shows that there are often many different ways to design the same data structure, and that a data structure should be designed for an anticipated pattern of use. 1. Theory. The most obvious way to represent a...
(Use the string class to solve the problem) Write a program (in c++) that can be...
(Use the string class to solve the problem) Write a program (in c++) that can be used to train the user to use less sexist language by suggesting alternative versions of sentences given by the user. The program will ask for a sentence, read the sentence into a string variable, and replace all occurrences of masculine pronouns with gender-neutral pronouns. For example, it will replace “he” with “she or he”, and “him” with “her or him”. Be sure to preserve...
Solve this Write a C++ class that implements a stack using a linked list. The type...
Solve this Write a C++ class that implements a stack using a linked list. The type of data contained in the stack should be double. The maximum size of the stack is 30. Implement the following methods: . · Constructor and destructor; // 5 pts · void push (double value); // pushes an element with the value into the stack. 5 pts. · double pop (); // pops an element from the stack and returns its value. 5 pts. ·...
Suppose the interface and the class of stack already implemented, Write application program to ( java)...
Suppose the interface and the class of stack already implemented, Write application program to ( java) 1- insert 100 numbers to the stack                         2- Print the even numbers 3- Print the summation of the odd numbers
JAVA Write a class for a Stack of characters using a linked list implementation. Write a...
JAVA Write a class for a Stack of characters using a linked list implementation. Write a class for a Queue of characters using a linked list implementation. Write a class for a Queue of integers using a circular array implementation.
In simple Java language algorithm: Implement a static stack class of char. Your class should include...
In simple Java language algorithm: Implement a static stack class of char. Your class should include two constructors. One (no parameters) sets the size of the stack to 10. The other constructor accepts a single parameter specifying the desired size of the stack a push and pop operator an isEmpty and isFull method . Both return Booleans indicating the status of the stack Using the stack class you created in problem 1), write a static method called parse that parses...
Please solve this problem in java. (simple linked list) public class MyLinkedList implements MiniList{ /* Private...
Please solve this problem in java. (simple linked list) public class MyLinkedList implements MiniList{ /* Private member variables that you need to declare: ** The head pointer ** The tail pointer */    private Node head;    private Node tail;       public class Node { // declare member variables (data and next)    Integer data;    Node next; // finish these constructors    public Node(int data, Node next) {               this.data=data;        this.next=next;    }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT