How do I create a program that reads an input file(a simple Java program) and ma
ID: 3681196 • Letter: H
Question
How do I create a program that reads an input file(a simple Java program) and matches the opening and closing braces together by inserting numbers after each brace, then displaying the enhanced input file on the console screen? The program must have organized methods(as many as needed). How do I create a program that reads an input file(a simple Java program) and matches the opening and closing braces together by inserting numbers after each brace, then displaying the enhanced input file on the console screen? The program must have organized methods(as many as needed).Explanation / Answer
import java.util.*;
public class ParenthesisMatching
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Stack<Integer> stk = new Stack<Integer>();
System.out.println("Parenthesis Matching Test ");
System.out.println("Enter expression");
String exp = scan.next();
int len = exp.length();
System.out.println(" Matches and Mismatches: ");
for (int i = 0; i < len; i++)
{
char ch = exp.charAt(i);
if (ch == '(')
stk.push(i);
else if (ch == ')')
{
try
{
int p = stk.pop() + 1;
System.out.println("'(' at index "+(i+1)+" matched with ')' at index "+p);
}
catch(Exception e)
{
System.out.println("')' at index "+(i+1)+" is unmatched");
}
}
}
while (!stk.isEmpty() )
System.out.println("'(' at index "+(stk.pop() +1)+" is unmatched");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.