I have used Stacks to check for brackets mismatch. (Parentheses matching problem using Stack algorithm)
Any suggestions on how to improve the code?
I have tried various examples and it works without error but I feel there is a lack of specificity. How do I work on that?
Side note: I think there's a stack reference type in Java but I am not allowed to use that.
import java.util.Scanner;
class ParensMatching
{
static Character Stack[]= new Character[25];
static int ptr = -1;
static void push(char ch)
{
if(ptr+1 < 25)
{
Stack[++ptr]= ch;
}
else
{
System.out.println("Overflow!! ");
}
}
static int pop()
{
if (ptr == -1)
{
System.out.println("Underflow!!");
return 999;
}
int value = Stack[ptr];
ptr = ptr-1;
return value;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.println("Enter a string");
String str = sc.nextLine();
char temp;
int i = 0;
outer:
for (i = 0; i< str.length(); i++)
{
if(str.charAt(i)== '('|| str.charAt(i)== '{' || str.charAt(i)== '[')
{
push(str.charAt(i));
temp = str.charAt(i);
}
else if(str.charAt(i)== ')')
{
if(pop()!= '(')
{
System.out.println("Unmathced parens, exitting! ");
break outer;
}
}
else if(str.charAt(i)== '}')
{
if(pop()!= '{')
{
System.out.println("Unmathced parens, exitting! ");
break outer;
}
}
else if(str.charAt(i)== ']')
{
if(pop()!= '[')
{
System.out.println("Unmathced parens, exitting! ");
break outer;
}
}
}
if(ptr != -1)
{
System.out.println("Missing closing parens!!");
}
else if (i == str.length())
{
System.out.println("Success. No unmatched parens");
}
System.out.println("Enter 2 to stop testing");
int n = sc.nextInt();
if(n == 2)
break;
else
continue;
}
}
}