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

Create a program named parentheses.java that reads in a string of various parent

ID: 666466 • Letter: C

Question

Create a program named parentheses.java that reads in a string of various parentheses, brackets, and braces from standard input. Using a stack, verify whether or not the parentheses, brackets, and braces are balanced by type (e.g. {] is not balanced).

Extra Credit: Modify your program so that it can solve an infix equation. E.g. (2 + 3) * (9 - 4)


Example output
This program checks if the parentheses, brackets, and braces are balanced.
Please enter a string:
(({}[()]{[]}))
This string is balanced.

This program checks if the parentheses, brackets, and braces are balanced.
Please enter a string:
{[])[()]}
This string is not balanced.

Explanation / Answer

package mani;

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

public class parentheses{
  
   public static boolean Parenthesis(String par) {
   if (par.charAt(0) == '{')
   return false;

   Stack<Character> pStack = new Stack<Character>();

   char s;
   for(int i=0; i < par.length(); i++) {
   s = par.charAt(i);

   if(s == '(')
   pStack.push(s);
   else if(s == '{')
   pStack.push(s);
   else if(s == ')')
   if(pStack.empty())
   return false;
   else if(pStack.peek() == '(')
   pStack.pop();
   else
   return false;
   else if(s == '}')
   if(pStack.empty())
   return false;
   else if(pStack.peek() == '{')
   pStack.pop();
   else
   return false;
   }
   return pStack.empty();
   }
   public static void main(String[] args){
       System.out.println("This program checks if the parentheses, brackets, and braces are balanced.");
       System.out.println("Please enter a string:");
       Scanner s=new Scanner(System.in);
       String par=s.next();
       boolean t=Parenthesis(par);
       if(t==true){
           System.out.println("This string is balanced.");
             
       }
       else{
           System.out.println("This string is not balanced.");
       }
   }

}

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