I wrote a program to check whether the given mathematical expression is correct or not but in the three test cases I had taken from web two of them getting correct output but one of the test case getting wrong output, but I don't know why..?
Test cases that I got right output are "(a+b)(a*b)" and "((a+b)". The test case that I'm getting wrong output is "(ab)(ab+)"
The code I tried is
public static void main(String[] args) {
// TODO code application logic here
Scanner sc=new Scanner(System.in);
String str=sc.next();
int l=str.length();
int a1=0,t=0,k=0;
for(int i=0;i<l;i++){
if(str.charAt(i)=='('){
a1++;
}else if(str.charAt(i)==')'){
a1--;
}
if(str.charAt(i)=='+'||str.charAt(i)=='-'||str.charAt(i)=='*'||str.charAt(i)=='/'){
k++;
if(str.charAt(--i)>='a'&&str.charAt(--i)<='z'&&str.charAt(++i)>='a'&&str.charAt(++i)<='z'){
t++;
}
}
}
if(a1==0&&t==k){
System.out.println("valid");
}else{
System.out.println("invalid");
}
}
The output expected for test case 3 is invalid but it gives valid as output.
You should not write .charAt(--i)
or .charAt(++i)
. Change it to i-1
and i+1
. What ++i
and --i
do is change the value of i
when it is being checked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.