Advertisement
geko444

SP1_W3

Feb 6th, 2020
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.StringReader;
  4. import java.util.Scanner;
  5. public class BalancedParentheses {
  6. public static void main(String[] args) {
  7. checkParentheses("((a + b) * t/2 * (1 - t)");
  8. checkParentheses("(a + b) * t)/(2 * (1 - t)");
  9. checkParentheses("a + ((a + b) * t)/(2 * (1 - t))");
  10. System.out.println("Enter an expression: ");
  11. Scanner scanner = new Scanner(System.in);
  12. String s = scanner.nextLine();
  13. checkParentheses(s);
  14. }
  15. public static void checkParentheses(String s) {
  16. System.out.println(s + " is "
  17. + (isBalanced(s) ? "" : "not ")
  18. + "parentheses balanced");
  19. }
  20. public static boolean isBalanced(String s) {
  21. BufferedReader br = new BufferedReader(new StringReader(s));
  22. int level = 0;
  23. int charInt;
  24.  
  25. try {
  26. while ((charInt = br.read()) != -1) {
  27. char c = (char) charInt;
  28. if (c == '(') {
  29. level++;
  30. } else if (c == ')') {
  31. level--;
  32. }
  33.  
  34. if (level < 0) {
  35. return false;
  36. }
  37. }
  38.  
  39. return level == 0;
  40. } catch (IOException e) {
  41. System.out.println(e.getMessage());
  42. return false;
  43. }
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement