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.
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 program to read in words from the given file “word.txt”. a. Prompt the...
Write a Java program to read in words from the given file “word.txt”. a. Prompt the user for two words b. Print out how many words in the file fall between those words c. If one of the two words is not contained in the file, print out which word is not found in the file d. If both words are not found in the file, print out a message e. Sample output: Please type in two words: hello computer...
I need to write a java program (in eclipse) that will read my text file and...
I need to write a java program (in eclipse) that will read my text file and replace specific placeholders with information provided in a second text file. For this assignment I am given a text file and I must replace <N>, <A>, <G>, with the information in the second file. For example the information can be John 22 male, and the template will then be modified and saved into a new file or files (because there will be multiple entries...
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional...
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional int array. Your program must (1) read the name of the file from the command-line arguments, (2) open the file, (3) check that each line has the same number of characters and (4) check that the only characters in a line are ones and zeros. If there is no such command-line argument or no such file, or if any of the checks fail, your...
Write a Java program to read in the 10 numbers in the example file Book1.csv provided...
Write a Java program to read in the 10 numbers in the example file Book1.csv provided above. The program should sum all the numbers, find the lowest number, find the highest number, and computer the average. Upon completion of the processing, the program should write a new text file named stats.txt with the information found in the following format where xxx represents a number calculated above. The sum of the numbers is: xxx The lowest number is: xxx The highest...
Write a java program that can create, read, and append a file. Assume that all data...
Write a java program that can create, read, and append a file. Assume that all data written to the file are string type. One driver class and a class that contains the methods. The program should have three methods as follows: CreateFile - only creating a file. Once it create a file successfully, it notifies to the user that it creates a file successfully. ReadingFile - It reads a contents of the file. This method only allow to read a...
Step by step in python please Write a program this will read a file (prompt for...
Step by step in python please Write a program this will read a file (prompt for name) containing a series of numbers (one number per line), where each number represents the radii of different circles. Have your program output a file (prompt for name) containing a table listing: the number of the circle (the order in the file) the radius of the circle the circumference the area of the circle the diameter of the circle Use different functions to calculate...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT