You should implement a syntax checking program that is similar to a function of compiler. Compliers...

Free

80.2K

Verified Solution

Question

Programming

You should implement a syntax checking program that is similarto a function of compiler. Compliers check programs for syntaxerrors, but frequently a lack of one symbol (such as a missingbrace or com-ment starter) will cause the complier to spill out ahundred lines of diagnostics without identifying the real error. Auseful tool in this situation is a program that checks whethereverything is balanced. Thus, every right brace, bracket, andparenthesis must correspond to its left counterpart. The sequence[()] is legal, but [()]) is wrong.

I get a runtime error, how can I solve this?

Answer & Explanation Solved by verified expert
3.7 Ratings (555 Votes)

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 {
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];
}
}


Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students