Use java to complete the following- A common problem for compilers and text edit
ID: 3811061 • 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. This is an essential step, there must be a prompt for input. 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
public class ParentesisCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Parentisis Expresion :");
String expr = sc.next();
if(isValid(expr))
System.out.println("Parentisis are valid");
else
System.out.println("Parentisis are not valid");
}
public static boolean isValid(String str)
{
if (str.isEmpty())
return true;
java.util.Stack<Character> stack = new java.util.Stack<Character>();
for (int i = 0; i < str.length(); i++)
{
char current = str.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return false;
char last = stack.peek();
if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
stack.pop();
else
return false;
}
}
return stack.isEmpty();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.