BEASTthisIndustry BEASTthisIndustry - 7 months ago 24
Java Question

Java Stack Boolean Output Customization?

So what I have is this slightly modified version of a code that's here a hundred times over for Java Stack Balancing.

import java.util.Stack;

public class Main {

public static String testContent = "{(a,b)}";

public static void main(String args[])
{

System.out.println(balancedParentheses(testContent));
}

public static boolean balancedParentheses(String s)
{
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' )
{
stack.push(c);
}else if(c == ']')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '[') return false;

}else if(c == ')')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '(') return false;

}else if(c == '}')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '{') return false;
}

}
return stack.isEmpty();
}
}


What I'd like to do is customize the output such that it would output something like "balanced" or "imbalanced" instead of true/false. Trying to replace return false; with a System.println containing 'balanced' gives me a whole lot of output lines I didn't want. Been searching around here for about an hour and some change and couldn't quite find the answer I was looking for. Any insight?

Answer

You could use something like

System.out.println(balancedParentheses(testContent) ? "balanced" : "imbalanced");

OR if you want a method that returns a String wrap the logic in another method

String isBalanced(String expression) {
    return balancedParentheses(expression) ? "balanced" : "imbalanced"
}

and in main()

System.out.println(isBalanced(testContent));

Also you could write the code something like this

public static boolean balancedParentheses(String s) {
    Stack<Character> stack = new Stack<Character>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '[' || c == '(' || c == '{') {
            stack.push(c);
        } else if (c == ']' || c == ')' || c == '}') {
            if (stack.isEmpty() || !matches(stack.pop(), c))
                return false;
        } 
    }
    return stack.isEmpty();
}

private static boolean matches(char opening, char closing) {
    return opening == '{' && closing == '}' ||
            opening == '(' && closing == ')' ||
            opening == '[' && closing == ']';
}
Comments