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

Create a java program using the following requirements Using the pseudocode algo

ID: 3828031 • Letter: C

Question

Create a java program using the following requirements

Using the pseudocode algorithm below, write a method that takes a String parameter and determines whether the enclosing punctuations are correctly nested. It will return true if they are, and false otherwise. You must account for parentheses, square brackets, and curly braces. Create an empty stack for characters For each character in the string if the character is '(' or '[' or '{' push it onto the stack else if the character is ')' or ']' or '}' if the stack is empty return false else pop a character from the stack if the popped character is not the left version of the character being considered return false endif endif endfor If the stack is not empty return false return true endif Also, write a main method that prompts the user for a string and then calls and prints the return value of the above method.

Explanation / Answer

import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Stack;

public class Parentheses {
private static final char L_PAREN = '(';
private static final char R_PAREN = ')';
private static final char L_BRACE = '{';
private static final char R_BRACE = '}';
private static final char L_BRACKET = '[';
private static final char R_BRACKET = ']';

public static boolean isBalanced(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {

if (s.charAt(i) == L_PAREN) stack.push(L_PAREN);

else if (s.charAt(i) == L_BRACE) stack.push(L_BRACE);

else if (s.charAt(i) == L_BRACKET) stack.push(L_BRACKET);

else if (s.charAt(i) == R_PAREN) {
if (stack.isEmpty()) return false;
if (stack.pop() != L_PAREN) return false;
}

else if (s.charAt(i) == R_BRACE) {
if (stack.isEmpty()) return false;
if (stack.pop() != L_BRACE) return false;
}

else if (s.charAt(i) == R_BRACKET) {
if (stack.isEmpty()) return false;
if (stack.pop() != L_BRACKET) return false;
}

// ignore all other characters

}
return stack.isEmpty();
}

public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
  
System.out.print("Enter an expression to check if it is balanced: " );
String s = sc.nextLine();
sc.close();
if(isBalanced(s))
{
System.out.println(args[0] + " is balanced");
}
else
{
System.out.println(args[0] + " 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