Pabroa 02-Quiz2

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

package pabroa_balancedjava;

import java.util.*;

public class Balanced {

public static void main(String[] args) {


Process process = new Process();

process.input();
}
}

class Process {

public void input() {


Stack<Character> stack = new Stack<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter symbols(2+): ");
String symbol = scanner.next();

if(isBalance(symbol, stack)){
System.out.println("Balanced!");
}else{
System.out.println("Not Balanced!");
}
}

// public int getCount(String symbol) {


// int i = 0;
// while (true) {
// if (symbol.charAt(i) != '\0') {
// i++;
// } else {
// break;
// }
//
// }
// return i;
// }

public boolean isBalance(String symbol, Stack<Character> stack){

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


if(stack.empty()){
stack.push(symbol.charAt(i));
}else if(stack.peek() == '(' && symbol.charAt(i) == ')'){
stack.pop();
}else{
stack.push(symbol.charAt(i));
}
}

return stack.empty();
}
}

You might also like