Question

In: Computer Science

Write a Java application "WellFormedExpression.java". Start with the file attached here. Please read the comments and...

Write a Java application "WellFormedExpression.java". Start with the file attached here.
Please read the comments and complete the function 'isWellFormed()'. It also has the main() to test the function with several input strings. Feel free to change and add more tests with different kinds of input data for correct implementation.
Note that you need MyStack.java and Stackinterface.java in the same package.

WellFormedExpression.java

package apps;

public class WellFormedExpression {
   static boolean isWellFormed(String s) {
       /**** Create a stack for Characters ****/
       char ch;
       for(int i=0; i<s.length();i++) {
           ch = s.charAt(i);
//           System.out.println(ch);              
           /************************************************
           if ch is a opening bracket, then push it to the stack
           else if ch is a closing bracket
                   if stack is empty, return false
                   if stack.pop() does not match the closing bracket, return false
           else ignore (do nothing)
          
           Assume that only three kinds of brackets are used - (), {}, []
           ************************************************/
          
       }
       // Here all characters are read. The stack should be empty to return true.
       return false; // change this to your need.
   }
   public static void main(String[] args) {
       // Example of using MyStack for Character
//       MyStack<Character> st = new MyStack<Character>();
//       st.push('a');
//       st.push('b');
//       System.out.println(st.pop());
//       System.out.println(st.isEmpty());
//       System.out.println(st.pop() == 'a');
      
       System.out.println(isWellFormed("(ab)")); // good
//       System.out.println(isWellFormed("(1+2)[]{3* 4}")); // good
//       System.out.println(isWellFormed("([]){}")); // good
//       System.out.println(isWellFormed("(((())))")); // good
//       System.out.println(isWellFormed("]")); // bad
//       System.out.println(isWellFormed("( xx [xxx) xx]")); // bad
//       System.out.println(isWellFormed("(()")); // bad
//       System.out.println(isWellFormed("())")); // bad
   }
}

StackInterface.java

package apps;

public interface StackInterface<E> {
   void push(E e);
   E pop();
   E peek();
   boolean isFull();
   boolean isEmpty();
}

MyStack.java

package apps;

public class MyStack<E> implements StackInterface<E>{
   E[] elements;
   int top;
   public MyStack() {
       elements = (E[]) new Object[5];
       top = 0;
   }
   private void enlarge() {
       E[] new_elements = (E[]) new Object[elements.length*2];
       for(int i=0; i<top; i++)
           new_elements[i] = elements[i];
       elements = new_elements;
   }
   public void push(E e) {
       if(isFull())
           enlarge();
       elements[top++] = e;
   }
   public E pop() {
       if(isEmpty())
           return null;
       return elements[top-- -1];
   }
   public E peek() {
       if(isEmpty())
           return null;
       return elements[top-1];
   }
   public boolean isFull() { return top == elements.length;}
   public boolean isEmpty() { return top == 0;}
}

Solutions

Expert Solution

package apps;

public class WellFormedExpression {
    static boolean isWellFormed(String s) {
        /**** Create a stack for Characters ****/
        MyStack<Character> st = new MyStack<Character>();
        char ch;
        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);
            // System.out.println(ch);
            /************************************************
             * if ch is a opening bracket, then push it to the stack
             * 
             * else if ch is a closing bracket if stack is empty, return false if
             * stack.pop() does not match the closing bracket, return false else ignore (do
             * nothing)
             * 
             * Assume that only three kinds of brackets are used - (), {}, []
             ************************************************/
            /** if ch is open bracket push to stack */
            if (ch == '(' || ch == '[' || ch == '{') {
                st.push(ch);
            } 
            /** if ch is closed bracket check if st.pop has its respective opening bracket */
            else if (ch == ')') {
                if (st.isEmpty() || st.pop() != '(') {
                    return false;
                } 
            } 
            else if (ch == ']') {
                if (st.isEmpty() || st.pop() != '[') {
                    return false;
                } 
            }
            else if (ch == '}') {
                if (st.isEmpty() || st.pop() != '{') {
                    return false;
                } 
            }

        }
        // Here all characters are read. The stack should be empty to return true.
        if (st.isEmpty()) {  // stk will be empty only if all open and closed brackets are correctly matched
            return true;
        }
        return false; // change this to your need.
    }

    public static void main(String[] args) {
        // Example of using MyStack for Character
        // MyStack<Character> st = new MyStack<Character>();
        // st.push('a');
        // st.push('b');
        // System.out.println(st.pop());
        // System.out.println(st.isEmpty());
        // System.out.println(st.pop() == 'a');


        /** output is true if it is well formed and false if it is not */
        System.out.println(isWellFormed("(ab)")); // good
        System.out.println(isWellFormed("(1+2)[]{3* 4}")); // good
        System.out.println(isWellFormed("([]){}")); // good
        System.out.println(isWellFormed("(((())))")); // good
        System.out.println(isWellFormed("]")); // bad
        System.out.println(isWellFormed("( xx [xxx) xx]")); // bad
        System.out.println(isWellFormed("(()")); // bad
        System.out.println(isWellFormed("())")); // bad
    }
}

Related Solutions

Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
JAVA Start with the SelectionSort class in the zip file attached to this item. Keep the...
JAVA Start with the SelectionSort class in the zip file attached to this item. Keep the name SelectionSort, and add a main method to it. Modify the selectionSort method to have two counters, one for the number of comparisons, and one for the number of data swaps. Each time two data elements are compared (regardless of whether the items are in the correct order—we're interested in that a comparison is being done at all), increment the comparison counter. Each time...
In Java. Modify the attached GameDriver2 to read characters in from a text file rather than...
In Java. Modify the attached GameDriver2 to read characters in from a text file rather than the user. You should use appropriate exception handling when reading from the file. The text file that you will read is provided. -------------------- Modify GaveDriver2.java -------------------- -----GameDriver2.java ----- import java.io.File; import java.util.ArrayList; import java.util.Scanner; /** * Class: GameDriver * * This class provides the main method for Homework 2 which reads in a * series of Wizards, Soldier and Civilian information from the user...
Hello, Please write this program in java and include a lot of comments and please try...
Hello, Please write this program in java and include a lot of comments and please try to make it as simple/descriptive as possible since I am also learning how to code. The instructions the professor gave was: Create your own class Your own class can be anything you want Must have 3 instance variables 1 constructor variable → set the instance variables 1 method that does something useful in relation to the class Create a driver class that creates an...
Using Java create an application that will read a tab-delimited file that displays the MLB standings...
Using Java create an application that will read a tab-delimited file that displays the MLB standings Below: League AL East Tampa Bay 37 20 NY Yankees 32 24 Toronto 29 27 Baltimore 23 33 Boston 22 34 League AL Central Minnesota 35 22 Chi White Sox 34 23 Cleveland 33 24 Kansas City 23 33 Detroit 22 32 League AL West Oakland 34 21 Houston 28 28 LA Angels 26 31 Seattle 25 31 Texas 19 37 League NL East...
Write a java application that will read a set of values from the user and stores...
Write a java application that will read a set of values from the user and stores them in array a[]. The application should ask the user for the number of values he will enter. You need to do the following methods: 1. Read: This method will read n values from the user and store them in an array a 2. Print: this method will print the array as given in the sample output 3. maxEven: This method will find the...
Write a Java program to read a set of integers from a file, dataX, and a...
Write a Java program to read a set of integers from a file, dataX, and a set of ranges from a second file, rangeX, and, for each range [a, b] in rangeX, report the SUM of all the integers in dataX which are in the range [a, b]. As the integers are read from file dataX, insert them in a binary search tree. After all the integers have been inserted into the binary search tree, read the ranges from file...
Write a java program that will read a file called stateinfo.txt and will store the information...
Write a java program that will read a file called stateinfo.txt and will store the information of the file into a map. The stateinfo.txt file contains the names of some states and their capitals. The format of stateinfo.txt file is as follows. State                Capital ---------                         ----------- NSW               Sydney VIC                 Melbourne WA                 Perth TAS                 Tasmania QLD                Brisbane SA                   Adelaide The program then prompts the user to enter the name of a state. Upon receiving the user input, the program should...
JAVA Assignment: Project File Processing. Write a program that will read in from input file one...
JAVA Assignment: Project File Processing. Write a program that will read in from input file one line at a time until end of file and output the number of words in the line and the number of occurrences of each letter. Define a word to be any string of letters that is delimited at each end by either whitespace, a period, a comma or the beginning or end of the line. You can assume that the input consists entirely of...
1. Write comments on each line of the uploaded Java file. 2. Add two more controls...
1. Write comments on each line of the uploaded Java file. 2. Add two more controls to the Java file. These controls are listed below. JTextField JRadioButton 3. Excecute your program and upload the following. 1. Image showing you have added the controls 2. Your updated Java files showing your comments and your added code for above two controls. --------------------------------------------------------------------------------------------------------------------------------- package swing; import javax.swing.*; public class SwingInheritance extends JFrame {    private static final long serialVersionUID = 1L;    SwingInheritance()...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT