Use java to complete the following- A common problem for compilers and text edit
ID: 3810564 • Letter: U
Question
Use java to complete the following-
A common problem for compilers and text editors is to determine if the parentheses (or other brackets) in a string are balanced and properly nested. For example, the string “((())())()” contains properly nested pairs of parentheses, but the string “)()(” does not, and the string “())” does not contain properly matching parentheses.
In this assignment the user is to enter an expression that contains parentheses. The program will then parse the expression checking to see if the parentheses are balanced or not. You should use a stack to implement this function.
Once parsed the program should return the position in the expression of the offending parenthesis if it is determined the parentheses are not balanced in the expression. The program needs to check if there is an excessive amount of right or left parentheses. If the parentheses in the expression are balanced the program should print out that they are.
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.Scanner;
import java.util.Stack;
public class BalancedParenthensies {
public static void main(String args[]) {
//System.out.println("()(){}{}{()} : balanced ? "+isBalanced("()(){}{}{()}"));
//System.out.println("((({}{}))()) : balanced ? "+isBalanced("((({}{]))())"));
Scanner sc = new Scanner(System.in);
System.out.print("Enter your input: ");
String input = sc.nextLine();
System.out.println(input + " is balance ? : "+isBalanced(input));
}
public static boolean isBalanced(String s) {
Stack<Character> stack = new Stack<Character>();
// scanning each character
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
}else if(c == ']') {
if(stack.isEmpty()) return false;
if(stack.pop() != '[') return false;
}else if(c == ')') {
if(stack.isEmpty()) return false;
if(stack.pop() != '(') return false;
}else if(c == '}') {
if(stack.isEmpty()) return false;
if(stack.pop() != '{') return false;
}
}
return stack.isEmpty();
}
}
/*
Sample run:
Enter your input: ()(){}{}{()}
()(){}{}{()} is balance ? : true
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.