Page ScheckParenthesis.javao Page CheckParenthesis,java 6 History B- public clas
ID: 3858072 • Letter: P
Question
Page ScheckParenthesis.javao Page CheckParenthesis,java 6 History B- public class CheckParenthesis { 16 17 E ex 18 19 201 21 x @param args the command line arguments public static void main(String[) args) 23 24 String input; Scanner s = new Scanner(System.in); System.out.print In(" Please input a set of parenthes is 25 26 27 28 29 30 31 input s . next ( ) ; Stack Output stk.nush(ch): main for (inti-o, i input, length(): i++) ParenthesisMatching (run) #2 run: Please input a set of parenthesis BUILD STOPPED (total time : 13 seconds) Downloading HTTP JavadocExplanation / Answer
Correct code for building is as follows:
import java.util.*;
import java.lang.*;
import java.io.*;
class CheckParenthesis
{
public static void main (String[] args) throws java.lang.Exception
{
String input;
Scanner s=new Scanner(System.in);
System.out.println("Please input a set of parentheses");
input=s.next();
//Stack<Character>stk=new Stack<>();//Error lies in this line of code,as you have not given the genric during object creation
Stack<Character>stk=new Stack<Character>();//Correct code
boolean valid=true;
char ch;
for(int i=0;i<input.length();i++)
{
ch=input.charAt(i);
if(ch=='(')
stk.push(ch);
else if(ch==')')
{
if(stk.empty())
{
valid=false;
break;
}
else
{
stk.pop();
}
}
}
if(!stk.empty())
valid=false;
if(valid)
System.out.println("--> Input is well formed");
else
System.out.println("--> Sorry,input is not well formed");
}
}
Sample Input:
()(
Sample Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.