In: Computer Science
You should implement a syntax checking program that is similar to a function of compiler. Compliers check programs for syntax errors, but frequently a lack of one symbol (such as a missing brace or com-ment starter) will cause the complier to spill out a hundred lines of diagnostics without identifying the real error. A useful tool in this situation is a program that checks whether everything is balanced. Thus, every right brace, bracket, and parenthesis must correspond to its left counterpart. The sequence [()] is legal, but [()]) is wrong.
I get a runtime error, how can I solve this?
This should work =]
import java.util.*;
import java.io.*;
public class Test
{
private static char[] stack=new char[100000];
private static int stackPoint=-1;
public static void main(String[] args) throws Exception
{
System.out.println("Enter file name: ");
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
String file=in.readLine();
Scanner scan=new Scanner(new FileReader(file));
out:while (scan.hasNext())
{
String stg=scan.nextLine();
for(int k=0; k<stg.length(); k++)
{
if(stg.charAt(k)=='{' || stg.charAt(k)=='(' ||
stg.charAt(k)=='[')
{
push(stg.charAt(k));
}
else if(k!=stg.length()-1 && stg.charAt(k)=='/' &&
stg.charAt(k+1)=='*')
{
push('/');
k++;
}
else if(stg.charAt(k)=='}' || stg.charAt(k)==')' ||
stg.charAt(k)==']')
{
char c=pop();
if(c=='-')
break out;
if(stg.charAt(k)=='}' && c!='{' || stg.charAt(k)==')'
&& c!='(' || stg.charAt(k)==']' && c!='[')
{
push(c);
break out;
}
}
else if(k!=stg.length()-1 && stg.charAt(k)=='*' &&
stg.charAt(k+1)=='/')
{
char c=pop();
if(c=='-')
break out;
if(c!='/')
{
push(c);
break out;
}
}
}
}
if(stackPoint==-1)
{
System.out.println("YES");
}
else
System.out.println("NO");
}
static void push(char c)
{
stackPoint++;
stack[stackPoint]=c;
}
static char pop()
{
stackPoint--;
if(stackPoint<=-2)
return '-';
return stack[stackPoint+1];
}
}