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

Write a program that checks whether or not a string of characters that has paren

ID: 641990 • Letter: W

Question

Write a program that checks whether or not a string of characters that has parenthesis is well formed. Write the method in the provided driver. Parenthesis are well formed if there is an open one then there must be matching closing one ). A stack is a good way to check. . Write in the method provided. Return true if the string was well formed and return false if it wasn?t . If there are no parenthesis in the string then it is well formed . The method char At may be something to look into . Use a stack to solve this When a (? is encountered push that one the stack When a )? is encountered pop off the stack If there is nothing to pop it is not well formed If the stack isn?t empty at the end then it is not well formed Example Dialog: Test number 0 is well formed! Test number 1 is well formed! Test number 2 is well formed! Test number 3 is wrong. All wrong Test number 4 is wrong. All wrong Test number 5 is well formed! Test number 6 is well formed!

Explanation / Answer

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


public class BalanceParenthesis {
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       String[] testArray ={"(a)",
               "((((()))))",
               "(asdf)((ababa)(((bob))))",
               "())",
               "((NOPE)",
               "This works I suppose",
               ""};
       for(int i=0;i<testArray.length;i++)
       {
           System.out.print("Test number "+i+" ");
           if(parenthesisChecker(testArray[i]))
           {
               System.out.println("is well formed!");
           }
           else
           {
               System.out.println("is wrong. All wrong");
           }
       }
   }
   public static boolean parenthesisChecker(String aString){
       Stack<Character> s = new Stack<Character>();
       for(int i = 0; i < aString.length(); ++i){
           if(aString.charAt(i) == '('){
               s.push(new Character(aString.charAt(i)));
           }
           else if(aString.charAt(i) == ')'){
               if(s.size() == 0){
                   return false;
               }
               else{
                   s.pop();
               }
           }
       }
       if(s.size() == 0){
           return true;
       }
       else{
           return false;
       }
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote