Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package parentThesisBalance;
- import java.util.Scanner;
- import java.util.*;
- public class CheckerPT {
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- try{
- Stack stack = new Stack();
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter a expression");
- String exp = sc.nextLine();
- boolean flag=false;
- for (int c = 0; c < exp.length(); c++) {
- char ch = exp.charAt(c);
- if (ch == '{' || ch == '(' || ch == '[') {
- stack.push(ch);
- }
- else if(ch=='}'||ch==')'||ch==']'){
- if(stack.isEmpty()){
- int found=exp.indexOf(ch);
- System.out.println("Error at character "+ ++found);
- System.out.println(ch+" not opened");
- }
- char popch=(char)stack.pop();
- int index=exp.indexOf(popch);
- if((ch=='}' && popch=='{')||(ch==')' && popch=='(')||(ch==']' && popch=='['))
- flag=true;
- else{
- flag=false;
- System.out.println("Expression is NOT correct");
- System.out.println("Error at character# "+ ++index);
- System.out.println(popch+" not closed");
- break;
- }
- }
- }
- if(flag)
- System.out.println("The expression is correct");
- }catch(Exception e){
- System.out.println(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement