Friday, 20 December 2019

Java Program to Check whether an expression is valid or not

//Expression validity check.
import java.util.*;
class ExpValidityCheck
{
public void check_Validity(String str)
{
int i=0,c=0,operand=0,operator=0,flag=1;
char ch;
for(i=0;i<str.length();i++)
{
ch=str.charAt(i);
if(ch>='A' && ch<='Z')
{
if(str.charAt(i+1)>='A' && str.charAt(i+1)<='Z')
{
flag=0;
break;
}
else
operand++;
}
else if((ch=='+')||(ch=='-')||(ch=='*')||(ch=='/')||(ch=='%'))
operator++;
else if(ch=='(')
{char ch1=str.charAt(i+1);
if((ch1=='+')||(ch1=='-')||(ch1=='*')||(ch1=='/')||(ch1=='%'))
{ flag=0;
break;
}
c++;
}
else if(ch==')')
{
c--;
if(c<0)
{
flag=0;
break;
}
char ch1=str.charAt(i-1);
if((ch1=='+')||(ch1=='-')||(ch1=='*')||(ch1=='/')||(ch1=='%'))
{ flag=0;
break;
}
}
}
if(flag==1)
{
if(operator + 1==operand)
System.out.println("Valid expression");
else
System.out.println("Invalid expression");
}
else
System.out.println("Invalid expression");
}
}

No comments:

Post a Comment

Convey your thoughts to authors.