Monday, August 29, 2011

Java Program to Check whether a Expression is Valid using Stack


The Program given below can be used to check whether a given mathematical expression is valid or invalid.The Validation procedure is based on the presence of complementary opening and closing braces.This implementation makes use of stack to push and pop out opening and closing brackets to the stack, as they are encountered in the Expression String.This program pushes opening brackets to the stack and pops out closing braces,checking whether the complementary brace is present at the top of the stack.Finally if the stack is empty the Expression is valid else the Expression is Invalid.

sample Output:
Enter the string
(a+b)-c
Valid Expression

Enter the string
(a+b-c
Invalid expression
The Complete Source Code is Provided below
 import java.io.*;  
 import java.lang.*;  
 class array  
 {  
  DataInputStream get=new DataInputStream(System.in);  
  int n,i,top=0,f=0;  
  char a[];  
  String str;  
  void getdata()  
  {  
  try  
   {  
   a=new char[30];  
   System.out.println("Enter the string");  
   str=get.readLine();  
   n=str.length();  
  }  
  catch(Exception e)  
  {  
   System.out.println(e.getMessage());  
  }  
  }  
  void push(char c)  
  {  
   a[top]=c;  
   top++;  
  }  
  char pop()  
  {  
   char h;  
  if(top!=0)  
   {  
   top--;  
   h=a[top];  
   return h;  
   }  
  else  
  return 0;  
  }  
  int stempty()  
  {  
   if(top==0)  
   return 1;  
   else  
   return 0;  
  }  
  void operation()  
  {  
  char d,t;  
  for(i=0;i<n;i++)  
   {  
   d=str.charAt(i);  
   switch(d)  
     {  
     case '(':  
         {  
          push(d);  
          break;  
         }  
     case '{':  
         {  
          push(d);  
          break;  
         }  
     case '[':  
         {  
          push(d);  
          break;  
         }  
     case ')':  
         {  
          t=pop();  
          if(t!='(')  
          f=1;  
          break;  
         }  
     case '}':  
         {  
          t=pop();  
          if(t!='{')  
          f=1;  
          break;  
         }  
     case ']':  
         {  
          t=pop();  
          if(t!='[')  
          f=1;  
          break;  
         }  
     }  
     }  
  if(f==0&&top==0)  
  {  
   System.out.println("Valid Expression");  
  }  
  else  
   System.out.println("Invalid expression");  
  }  
 }  
 class validexp  
 {  
  public static void main(String arg[])  
  {  
   array obj=new array();  
   obj.getdata();  
   obj.operation();   
  }  
 }  

4 comments:

Post a Comment

Subscribe

The Source Codes Published in this Blog can be used freely for Educational purposes but should not be reproduced on any other Blog or Website without the consent of the author.