Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.StringReader;
- import java.util.Scanner;
- public class BalancedParentheses {
- public static void main(String[] args) {
- checkParentheses("((a + b) * t/2 * (1 - t)");
- checkParentheses("(a + b) * t)/(2 * (1 - t)");
- checkParentheses("a + ((a + b) * t)/(2 * (1 - t))");
- System.out.println("Enter an expression: ");
- Scanner scanner = new Scanner(System.in);
- String s = scanner.nextLine();
- checkParentheses(s);
- }
- public static void checkParentheses(String s) {
- System.out.println(s + " is "
- + (isBalanced(s) ? "" : "not ")
- + "parentheses balanced");
- }
- public static boolean isBalanced(String s) {
- BufferedReader br = new BufferedReader(new StringReader(s));
- int level = 0;
- int charInt;
- try {
- while ((charInt = br.read()) != -1) {
- char c = (char) charInt;
- if (c == '(') {
- level++;
- } else if (c == ')') {
- level--;
- }
- if (level < 0) {
- return false;
- }
- }
- return level == 0;
- } catch (IOException e) {
- System.out.println(e.getMessage());
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement