Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please fix the error so that the java program runs // ? ? ? ?“ ParenMatch.java /

ID: 3912233 • Letter: P

Question

Please fix the error so that the java program runs

// ? ? ? ?“ ParenMatch.java / Determines whether or not a string of characters contains matehing left and right parentheses import java.util. import java.util.scanner public class ParenMatch public static void main (String1 args) Stack s -new Stack) String line Scanner scan-new Scanner (System.in) // the string of characters to be checked System.out.println (" Parenthesis Matching System.out.print "Enter a parenthesized expression: line scan.nextLine /1 loop to process the 1ine one character at a time // print the results

Explanation / Answer

ParenMatch.java

import java.util.Scanner;

import java.util.Stack;

public class ParenMatch {

public static void main(String[] args) {

Stack<Integer> s = new Stack<Integer>();

String line;

Scanner scan = new Scanner(System.in);

System.out.println(" Parenthesis Matching");

System.out.println("Enter a parenthesized expression: ");

line = scan.nextLine();

for(int i=0; i < line.length(); i++) {

char ch = line.charAt(i);

if (ch == '(')

s.push(i);

else if (ch == ')')

{

try

{

int p = s.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 (!s.isEmpty() )

System.out.println("'(' at index "+(s.pop() +1)+" is unmatched");

}

}

Output:


Parenthesis Matching
Enter a parenthesized expression:
(a+(b*c)-d
')' at index 8 matched with ')' at index 4
'(' at index 1 is unmatched


Parenthesis Matching
Enter a parenthesized expression:
(a+(b*c)-d)
')' at index 8 matched with ')' at index 4
')' at index 11 matched with ')' at index 1