Checking if parentheses match always saying that they match - java

I am writing a program where I should check if the opening parenthesis matches the closing one. If it doesn't match, I should display No. Otherwise, I should display yes.
This is the function I wrote, taking the input from the input buffer. However, I just keep on receiving yes for the second test case, instead of YES NO YES but the other two cases are correct.
static String[] braces(String[] values) {
Stack<Character> st = new Stack<Character>();
String[] answer = new String[values.length];
for(int i =0; i<values.length;i++){
char[] crt = values[i].toCharArray();
for(char c : crt){
switch(c){
case '{':
case '(':
case '[':
st.push(c);
break;
case '}':
if(st.isEmpty() || (st.peek() != '{'))
{
answer[i]= "NO";
break;
}
st.pop();
case ')':
if(st.isEmpty() || (st.peek() != '('))
{
answer[i]= "NO";
break;
}
st.pop();
case ']':
if(st.isEmpty() || (st.peek() != '['))
{
answer[i]= "NO";
break;
}
st.pop();
}
}
if(st.isEmpty() && answer[i].equals("NO") ){
answer[i]="YES";
System.out.println("I set answer[" + i + "] = YES due to stack being empty");
}
else
{
answer[i]="NO";
System.out.println("I set answer[" + i + "] = NO due to stack being non-empty");
}
st.clear();
}
return answer;
}

Change stack.firstElement() to stack.peek(), you need the stack top instead of the first element. (firstElement is not a Stack method)

The great secret of StackOverflow is that it's not actually full of gurus who look at your code the way Neo looks at The Matrix. It's just people examining how your programs runs.
You can do this yourself, and the most ancient and trivial way is through so-called "print debugging".
In short, you just add print statements that prints what your code is doing, and then you follow along and compare it to what you think it should be doing. Here's your code with such print statements added:
import java.util.*;
public class Test {
static String[] braces(String[] values) {
Stack<Character> st = new Stack<Character>();
String[] answer = new String[values.length];
for(int i =0; i<values.length;i++){
char[] crt = values[i].toCharArray();
boolean an = false;
for(char c : crt){
switch(c){
case '{':
case '(':
case '[':
st.push(c);
break;
case '}':
if(st.isEmpty() || (st.firstElement() != '{'))
{
answer[i]= "NO";
System.out.println("I set answer[" + i + "] = NO due to mismatched }");
}
st.pop();
break;
case ')':
if(st.isEmpty() || (st.firstElement() != '('))
{
answer[i]= "NO";
System.out.println("I set answer[" + i + "] = NO due to mismatched )");
}
st.pop();
break;
case ']':
if(st.isEmpty() || (st.firstElement() != '['))
{
answer[i]= "NO";
System.out.println("I set answer[" + i + "] = NO due to mismatched ]");
}
st.pop();
break;
}
}
if(st.isEmpty()){
answer[i]="yes";
System.out.println("I set answer[" + i + "] = YES due to stack being empty");
}
else
{
answer[i]="no";
System.out.println("I set answer[" + i + "] = NO due to stack being non-empty");
}
st.clear();
}
return answer;
}
public static void main(String[] args) {
String[] result = braces(new String[] { "(foo}" });
for(String s : result) System.out.println("The final result is " + s);
}
}
And here's the output, running on the string (foo}:
I set answer[0] = NO due to mismatched }
I set answer[0] = YES due to stack being empty
The final result is yes
Welp, it looks like you're overwriting your previous answer. You should make sure the final test doesn't override the loop's conclusion.
The trivial hack would be to check if answer[i] is null, but the better way would be to create a second helper method boolean braces(String) that is free to return true or false at any time, and then simply call that function in a loop in your braces(String[])
In any case, this would have been my implementation:
import java.util.Stack;
class Test {
static char flip(char c) {
switch(c) {
case '}': return '{';
case ')': return '(';
case ']': return '[';
default: throw new IllegalArgumentException("Invalid paren " + c);
}
}
static boolean matched(String value) {
Stack<Character> st = new Stack<Character>();
for (int i=0; i<value.length(); i++) {
char c = value.charAt(i);
switch(c) {
case '{':
case '(':
case '[':
st.push(c);
break;
case '}':
case ')':
case ']':
if (st.isEmpty() || st.peek() != flip(c)) {
return false;
}
st.pop();
break;
}
}
return st.isEmpty();
}
static String[] braces(String[] values) {
String[] result = new String[values.length];
for(int i=0; i<result.length; i++) {
result[i] = matched(values[i]) ? "yes" : "no";
}
return result;
}
public static void main(String[] args) {
String[] input = new String[] { "}", "{}", "{()}", "asdf", "", "{[", "{[[([])]]}", "((foo))" };
String[] actual = braces(input);
String[] expected = new String[] { "no", "yes", "yes", "yes", "yes", "no", "yes", "yes" };
for(int i=0; i<actual.length; i++) {
if(!actual[i].equals(expected[i])) {
System.out.println("Failed: " + input[i] + " should have been " + expected[i]);
System.exit(1);
}
}
System.out.println("OK");
}
}

import java.util.*;
import java.util.stream.Collectors;
public class Test {
static final Map<Character, Character> PARENS;
static final Set<Character> CLOSING_PARENS;
static {
PARENS = new HashMap<>();
PARENS.put('{', '}');
PARENS.put('[', ']');
PARENS.put('(', ')');
CLOSING_PARENS = new HashSet<>(PARENS.values());
}
public static void main(String[] args) {
print(braces("(foo}","[]","()","{}","[{}]","([{}])","[[]]"));
print(braces("[","]","][","[{]}"));
// test case 2 ...
print(braces("{[()]}","{[(])}","{{[[(())]]}}"));
// ... prints YES NO YES ...
}
static void print(String ... values){
for(String str : values){
System.out.print(str + " ");
}
System.out.println();
}
static String [] braces(String ... values) {
return Arrays.stream(values)
.map(Test::isBalanced)
.map(b -> b ? "YES" : "NO")
.collect(Collectors.toList()).toArray(new String[values.length]);
}
static boolean isBalanced(String token){
Stack<Character> stack = new Stack<>();
for(char c : token.toCharArray()){
if (PARENS.keySet().contains(c)){
stack.push(c);
} else if(CLOSING_PARENS.contains(c)){
if(stack.isEmpty() || !PARENS.get(stack.pop()).equals(c)) {
return false;
}
}
}
return stack.isEmpty();
}
}

you just have to make the following changes
Replace firstElement() with peek() in all cases
remove the following statement from the first two cases
stack.pop();
break;
check if stack is empity at the last case
if(!stack.isEmpty())
corrected code:
public class ParenMatch{
public static void main(String[] args){
String[] str = { "{}[](){[}]","{[()]}{[(])}{{[[(())]]}}","", "}][}}(}][))][](){()}()({}([][]))[](){)[](}]}]}))}(())(([[)"};
System.out.println(Arrays.toString(braces(str)));
}
public static String[] braces(String[] values)
{
Stack<Character> stack = new Stack<Character>();
String[] isCorrect = new String[values.length];
for (int i = 0; i < values.length; i++)
{
char[] crt = values[i].toCharArray();
boolean an = false;
for (char c : crt)
{
switch(c)
{
case '{':
case '(':
case '[':
stack.push(c);
break;
case '}':
if (stack.isEmpty() || (stack.peek() != '{'))
{
isCorrect[i] = "NO";
}
//stack.pop();
//break;
case ')':
if (stack.isEmpty() || (stack.peek() != '('))
{
isCorrect[i] = "NO";
}
//stack.pop();
//break;
case ']':
if (stack.isEmpty() || (stack.peek() != '['))
{
isCorrect[i] = "NO";
}
if(!stack.isEmpty())
stack.pop();
break;
}
}
if (stack.isEmpty())
{
isCorrect[i] = "yes";
}
else
{
isCorrect[i] = "no";
}
stack.clear();
}
return isCorrect;
}
}
input:
String[] str = { "{}[](){[}]","{[()]}{[(])}{{[[(())]]}}","", "}][}}(}][))][](){()}()({}([][]))[](){)[](}]}]}))}(())(([[)"};
output:
[yes, yes, yes, no]

static String[] braces(String[] values) {
Stack<Character> st = new Stack<Character>();
String []answer = new String[values.length];
Boolean isCorrect = false;
for(int i =0; i< values.length;i++)
{
isCorrect = true;
st.clear();
char crt[] = values[i].toCharArray();
for(char c : crt)
{
switch(c)
{
case'{':
case'[':
case'(':
st.push(c);
break;
case'}':
if(st.isEmpty() || st.peek() != '{')
{
System.out.println("Hellooo");
answer[i] ="NO";
isCorrect = false;
}
if(!st.isEmpty())
{
st.pop();
}
break;
case']':
if(st.isEmpty() || st.peek() != '[')
{
System.out.println("Hell");
answer[i] ="NO";
isCorrect = false;
}
if(!st.isEmpty())
{
st.pop();
}
break;
case')':
if(st.isEmpty() || st.peek() != '(')
{
isCorrect = false;
}
if(!st.isEmpty()) {
st.pop();
}
break;
}
}
if(isCorrect && st.isEmpty())
{
answer[i] = "YES";
System.out.println("Hello");
}else answer[i] = "NO";
}
return answer;
}

Related

How do I fix this output problem with my (), [], {} checker?

The problem is after scanning the file called "confused.dat" it outputs 90% of what it is supposed to and the other 10% are incorrect.
I have tried exchanging methods of scanning the file but nothing really changed.
import java.util.Scanner;
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
public class confused {
public static boolean isBalanced(String inp) {
if ((inp.length() % 2) == 1){ return false;}
else {
Stack<Character> s = new Stack<>();
for (char brackBrick : inp.toCharArray())
switch (brackBrick) {
case '{': s.push('}'); break;
case '(': s.push(')'); break;
case '[': s.push(']'); break;
default : if (s.isEmpty() || brackBrick != s.peek()) { return false;}
s.pop();
}
return s.isEmpty();
}
}
public static void main(String[] args) /*throws FileNotFoundException*/ {
try{
Scanner scrn = new Scanner (new File("confused.dat"));
while (scrn.hasNextLine()){
boolean answer = isBalanced(scrn.nextLine());
if (answer) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
} catch (FileNotFoundException e){e.printStackTrace();}
}
}
confused.dat file:
([])
(([()])))
([()[]()])()
(([()])
([] )
(([()])))
([()[]()])()
(
(]
)(
][
Here is expected output vs. the actual output
https://imgur.com/cciHkGL
shouldn't it be a no, because
if ((inp.length() % 2) == 1){ return false;}
if (answer) {
System.out.println("Yes");
} else {
System.out.println("No");
(([()]))) is not a even number, so therefore it false, and thus will print no.
Oh, I think I got it. You were actually pretty close. First off, drop this line
if ((inp.length() % 2) == 1){ return false;}
and then ignore empty spaces by adding the following condition in your switch statement:
case ' ': break;
So all in all the updated method now looks like this
public static boolean isBalanced(String inp) {
Stack<Character> s = new Stack<>();
for (char brackBrick : inp.toCharArray()) {
switch (brackBrick) {
case '{': s.push('}'); break;
case '(': s.push(')'); break;
case '[': s.push(']'); break;
case ' ': break;
default : if (s.isEmpty() || brackBrick != s.peek()) { return false;}
s.pop();
}
}
return s.isEmpty();
}
You should now get the following output
Yes
Yes
No
Yes
No
Yes
No
Yes
No
No
No
No

Conversion of an infix operation to a postfix operation

The code takes in an infix operation and converts it to a postfix operation. I have been able to to the conversion. The problem I'm facing is the spacing between operators. Also, I'd like to know how the postfix operation can be evaluated.
import java.io.IOException;
public class InToPost {
private Stack theStack;
private String input;
private String output = "";
public InToPost(String in) {
input = in;
int stackSize = input.length();
theStack = new Stack(stackSize);
}
public String doTrans() {
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
switch (ch) {
case '+':
case '-':
gotOper(ch, 1);
break;
case '*':
case '/':
case '%':
gotOper(ch, 2);
break;
case '(':
theStack.push(ch);
break;
case ')':
gotParen(ch);
break;
default:
output = output + ch;
break;
}
}
while (!theStack.isEmpty()) {
output = output + theStack.pop();
}
System.out.println(output);
return output;
}
public void gotOper(char opThis, int prec1) {
while (!theStack.isEmpty()) {
char opTop = theStack.pop();
if (opTop == '(') {
theStack.push(opTop);
break;
}
else {
int prec2;
if (opTop == '+' || opTop == '-')
prec2 = 1;
else
prec2 = 2;
if (prec2 < prec1) {
theStack.push(opTop);
break;
}
else
output = output + opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char ch){
while (!theStack.isEmpty()) {
char chx = theStack.pop();
if (chx == '(')
break;
else
output = output + chx;
}
}
public static void main(String[] args)
throws IOException {
String input = "13 + 23 - 42 * 2";
String output;
InToPost theTrans = new InToPost(input);
output = theTrans.doTrans();
System.out.println("Postfix is " + output + '\n');
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
The postfix output for this is:
13 23 + 42 2*-
whereas I am trying to get an output that looks like this:
13 23 + 42 2 * -
I am unable to space the operator in the output.

Unknown error in converting a multiple digit infix expression to postfix

The function code for converting infix to postfix expression, as follows
package swapnil.calcii;
import android.util.Log;
import java.util.Stack;
public class Calculate {
private static final String operators = "-+/*";
private static final String operands = "0123456789";
public int evalInfix(String infix) {
return evaluatePostfix(convert2Postfix(infix));
}
public String convert2Postfix(String infixExpr) {
char[] chars = infixExpr.toCharArray();
Stack<String> stack = new Stack<String>();
StringBuilder out = new StringBuilder(infixExpr.length());
for (char c : chars) {
if (isOperator(c)) {
while (!stack.isEmpty() && !stack.peek().equals("(")) {
if (operatorGreaterOrEqual(stack.peek(), c)) {
out.append(stack.pop());
} else {
break;
}
}
String s = ""+c;
stack.push(s);
}
else if (c == '(') {
String s = ""+c;
stack.push(s);
} else if (c == ')') {
while (!stack.isEmpty() && !stack.peek().equals("(")) {
out.append(stack.pop());
}
if (!stack.isEmpty()) {
stack.pop();
}
} else if (isOperand(c)) {
try{
StringBuilder num = new StringBuilder();
while(isOperand(stack.peek().charAt(0))) {
num.append(stack.pop());
out.append(num);
}
} catch (Exception e) {
Log.d("errrr", "error in inserting " + e.getMessage());
out.append(c);
}
out.append(c);
}
}
while (!stack.empty()) {
out.append(stack.pop());
}
return out.toString();
}
public int evaluatePostfix(String postfixExpr) {
char[] chars = postfixExpr.toCharArray();
Stack<Integer> stack = new Stack<Integer>();
for (char c : chars) {
if (isOperand(c)) {
stack.push(c - '0'); // convert char to int val
} else if (isOperator(c)) {
int op1 = stack.pop();
int op2 = stack.pop();
int result;
switch (c) {
case '*':
result = op1 * op2;
stack.push(result);
break;
case '/':
result = op2 / op1;
stack.push(result);
break;
case '+':
result = op1 + op2;
stack.push(result);
break;
case '-':
result = op2 - op1;
stack.push(result);
break;
}
}
}
return stack.pop();
}
private int getPrecedence(char operator) {
int ret = 0;
if (operator == '-' || operator == '+') {
ret = 1;
} else if (operator == '*' || operator == '/') {
ret = 2;
}
return ret;
}
private boolean operatorGreaterOrEqual(String op1, char op2) {
char op = op1.charAt(0);
return getPrecedence(op) >= getPrecedence(op2);
}
private boolean isOperator(char val) {
return operators.indexOf(val) >= 0;
}
private boolean isOperand(char val) {
return operands.indexOf(val) >= 0;
}
}
crashes with unknown error.
I've written it myself and I can't figure out where I am going wrong.
Function works fine, if pushing one char when checking isOperand(c)
But using StringBuilder to push a multiple digit number crashes the code.
Help

Java print certain characters from an array

I have a string array that looks like this:
[67, +, 12, -, 45]
I want to print it out so that it looks like this:
67 12 + 45 -
Here's the code I'm trying to use to do this.
String[] temp = line.split(" ");
String tmp = line.replaceAll("\\s+","");
for(int i = 0; i < temp.length; i++)
{
if(isInt(temp[i]) == false)
{
expression = temp[i];
firstExp = true;
}
else if(isInt(temp[i]) == false && firstExp == true && secondExp == false)
{
System.out.print(expression);
secondExp = true;
}
else if(isInt(temp[i]) == false && firstExp == true && secondExp == true)
{
System.out.print(expression);
firstExp = false;
secondExp = false;
}
else
{
System.out.print(temp[i]);
}
}
firstExp and secondExp are Booleans that check for the expressions that should appear in the array. isInt() is just a method used to determine if the string is a number. Right now, all this code does is output this:
671245
public static void main (String[] args) throws java.lang.Exception
{
String[] expr = new String[]{"67", "+", "45", "-", "12", "*", "5", "/", "78"};
int current = 0;
StringBuilder postfix = new StringBuilder();
// handle first three
postfix.append(expr[current]).append(" ");
postfix.append(expr[current+2]).append(" ");
postfix.append(expr[current+1]).append(" ");
current += 3;
// handle rest
while( current <= expr.length-2 ){
postfix.append(expr[current+1]).append(" ");
postfix.append(expr[current]).append(" ");
current += 2;
}
System.out.println(postfix.toString());
}
Outputs:
67 45 + 12 - 5 * 78 /
You can run/edit this at: http://ideone.com/zcdlEq
I guess what you are trying to do is converting infix expression to post fix. Some time back I had written the following code:
public class InfixToPostfix {
private Stack stack;
private String input;
private String output = "";
public InfixToPostfix(String in) {
input = in;
int stackSize = input.length();
stack = new Stack(stackSize);
}
public String translate() {
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
switch (ch) {
case '+':
case '-':
hastOperator(ch, 1);
break;
case '*':
case '/':
hastOperator(ch, 2);
break;
case '(':
stack.push(ch);
break;
case ')':
hasSuperior(ch);
break;
default:
output = output + ch;
break;
}
}
while (!stack.isEmpty()) {
output = output + stack.pop();
}
System.out.println(output);
return output;
}
public void hastOperator(char op, int precedence) {
while (!stack.isEmpty()) {
char opTop = stack.pop();
if (opTop == '(') {
stack.push(opTop);
break;
}
else {
int prec2;
if (opTop == '+' || opTop == '-')
prec2 = 1;
else
prec2 = 2;
if (prec2 < precedence) {
stack.push(opTop);
break;
}
else
output = output + opTop;
}
}
stack.push(op);
}
public void hasSuperior(char ch){
while (!stack.isEmpty()) {
char chx = stack.pop();
if (chx == '(')
break;
else
output = output + chx;
}
}
public static void main(String[] args)
throws IOException {
String input = "67 + 12 - 45";
String output;
InfixToPostfix theTrans = new InfixToPostfix(input);
output = theTrans.translate();
System.out.println("Postfix is " + output + '\n');
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}
You may need to modify this program to read from an array, but that is very trivial.
Here's how you do it in one line:
System.out.println(Arrays.toString(temp).replaceAll("[^\\d +*/-]", "").replaceAll("[+*/-]) (\\d+)", "$2 $1"));

Postfix stack calculator

I've created a stack calculator for my Java class to solve equations such as
2 + ( 2 * ( 10 – 4 ) / ( ( 4 * 2 / ( 3 + 4) ) + 2 ) – 9 )
2 + { 2 * ( 10 – 4 ) / [ { 4 * 2 / ( 3 + 4) } + 2 ] – 9 }
We are suppose to implement { } [ ] into our code. I did it with just parentheses. It works 100% with just ( ). When I try to add { } [ ], it goes bananas.
This is what I have so far:
package stackscalc;
import java.util.Scanner;
import java.util.Stack;
import java.util.EmptyStackException;
class Arithmetic {
int length;
Stack stk;
String exp, postfix;
Arithmetic(String s) {
stk = new Stack();
exp = s;
postfix = "";
length = exp.length();
}
boolean isBalance() {
boolean fail = false;
int index = 0;
try {
while (index < length) {
char ch = exp.charAt(index);
switch(ch) {
case ')':
stk.pop();
break;
case '(':
stk.push(new Character(ch));
break;
default:
break;
}
index++;
}
} catch (EmptyStackException e) {
fail = true;
}
return stk.empty() && !fail;
}
void postfixExpression() {
String token = "";
Scanner scan = new Scanner(exp);
stk.clear();
while(scan.hasNext()) {
token = scan.next();
char current = token.charAt(0);
if (isNumber(token)) {
postfix = postfix + token + " ";
} else if(isParentheses(current)) {
if (current == '(') {
stk.push(current);
} else {
Character ch = (Character) stk.peek();
char nextToken = ch.charValue();
while(nextToken != '(') {
postfix = postfix + stk.pop() + " ";
ch = (Character) stk.peek();
nextToken = ch.charValue();
}
stk.pop();
}
} else {
if (stk.empty()) {
stk.push(current);
} else {
Character ch = (Character) stk.peek();
char top = ch.charValue();
if (hasHigherPrecedence(top, current)) {
stk.push(current);
} else {
ch = (Character) stk.pop();
top = ch.charValue();
stk.push(current);
stk.push(top);
}
}
}
}
try {
Character ch = (Character) stk.peek();
char nextToken = ch.charValue();
while (isOperator(nextToken)) {
postfix = postfix + stk.pop() + " ";
ch = (Character) stk.peek();
nextToken = ch.charValue();
}
} catch (EmptyStackException e) {}
}
boolean isNumber(String s) {
try {
int Num = Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
void evaluateRPN() {
Scanner scan = new Scanner(postfix);
String token = "";
stk.clear();
while(scan.hasNext()) {
try {
token = scan.next();
if (isNumber(token)) {
stk.push(token);
} else {
char current = token.charAt(0);
double t1 = Double.parseDouble(stk.pop().toString());
double t2 = Double.parseDouble(stk.pop().toString());
double t3 = 0;
switch (current) {
case '+': {
t3 = t2 + t1;
stk.push(t3);
break;
}
case '-': {
t3 = t2 - t1;
stk.push(t3);
break;
}
case '*': {
t3 = t2 * t1;
stk.push(t3);
break;
}
case '/': {
t3 = t2 / t1;
stk.push(t3);
break;
}
default: {
System.out.println("Reverse Polish Notation was unable to be preformed.");
}
}
}
} catch (EmptyStackException e) {}
}
}
String getResult() {
return stk.toString();
}
int stackSize() {
return stk.size();
}
boolean isParentheses(char current) {
if ((current == '(') || (current == ')')) {
return true;
} else {
return false;
}
}
boolean isOperator(char ch) {
if ((ch == '-')) {
return true;
} else if ((ch == '+')) {
return true;
}
else if ((ch == '*')) {
return true;
}
else if((ch == '/')) {
return true;
} else {
}
return false;
}
boolean hasHigherPrecedence(char top, char current) {
boolean HigherPre = false;
switch (current) {
case '*':
HigherPre = true;
break;
case '/':
HigherPre = true;
break;
case '+':
if ((top == '*') || (top == '/') || (top == '-')) {
HigherPre = false;
} else {
HigherPre = true;
}
break;
case '-':
if ((top == '*') || (top == '/') || (top == '-')) {
HigherPre = false;
} else {
HigherPre = true;
}
break;
default:
System.out.println("Higher Precedence Unsuccessful was unable to be preformed.");
break;
}
return HigherPre;
}
String getPostfix() {
return postfix;
}
}
What I am assuming is that (), {}, and [] all have the same weight in terms of order of operations, and you just need to modify your code in order to allow for all three interchangeably.
If that is the case, I would just use the matcher class with a simple regex check to see if the current char that you are looking at is either a parenthesis, curly brace, or bracket.
//convert char to string
String temp += currentChar;
//this will check for (, [, and { (need escapes because of how regex works in java)
Pattern bracePattern = Pattern.compile("[\(\{\[]");
Matcher matcher = numPatt.matcher(temp);
if(matcher.find()){
//you know you have a grouping character
}
This code should allow you to find all the opening grouping characters (just substitute (,{, and [ for ),} and ] in the regex to find closing characters). This can be used in your isParenthesis() method.
You could use a method like this to streamline checking if a '(', '[', or '{' is matched or not.
static char getExpected(char val){
char expected=' ';
switch (val) {
case '(':
expected=')';
break;
case '[':
expected=']';
break;
case '{':
expected='}';
break;
}
return expected;
}

Categories