Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company;
- import java.io.*;
- import java.util.Scanner;
- public class Main {
- public static int Pntr = 0;
- public static void main(String[] args) throws Exception{
- System.out.println("This program will check the balance of the brackets in the lines");
- IsBracketCorrect();
- }
- public static char OpenBracket(final char Ch) {
- switch (Ch) {
- case (')'): return('(');
- case (']'): return('[');
- case ('}'): return ('{');
- default: return ('0');
- }
- }
- public static void Push(char[] MassStack, char Ch ) {
- MassStack[Pntr] = Ch;
- Pntr++;
- }
- public static char Pop(char[] MassStack) {
- Pntr--;
- if (Pntr > -1) {
- return (MassStack[Pntr]);
- }
- else {
- return ('0');
- }
- }
- public static boolean Proc(String StrSrc) {
- int i = 0;
- Pntr = 0;
- char [] MassStack = new char[100];
- boolean Balance = true;
- while ((i < StrSrc.length()) && Balance) {
- if ((StrSrc.charAt(i) == '(') || (StrSrc.charAt(i) == '[') || (StrSrc.charAt(i) == '{')) {
- Push(MassStack, StrSrc.charAt(i));
- }
- else {
- if ((StrSrc.charAt(i) == ')') || (StrSrc.charAt(i) == ']') || (StrSrc.charAt(i) == '}')) {
- if (Pop(MassStack) != OpenBracket(StrSrc.charAt(i))) {
- Balance = false;
- }
- }
- }
- i++;
- }
- return((Pntr == 0) && Balance);
- }
- public static boolean isStrCorrect(String StrSrc) {
- boolean isCorrect = false;
- for (int i = 0; i < StrSrc.length(); i++) {
- if ((StrSrc.charAt(i) == '(') || (StrSrc.charAt(i) == '[') || (StrSrc.charAt(i) == '{') || (StrSrc.charAt(i) == ')') || (StrSrc.charAt(i) == ']') || (StrSrc.charAt(i) == '}')) {
- isCorrect = true;
- }
- }
- return (isCorrect);
- }
- public static String FileNameInputRead() throws Exception {
- boolean isCorrect = true;
- String FileName;
- do {
- System.out.println("Enter file name:");
- Scanner scan = new Scanner(System.in);
- FileName = scan.next();
- File FileIn = new File(FileName);
- if (FileIn.exists()) {
- isCorrect = false;
- }
- else {
- System.out.println("This file does not exist!");
- }
- }
- while (isCorrect);
- return (FileName);
- }
- public static void IsBracketCorrect() throws Exception {
- String FileName = FileNameInputRead();
- String StrSrc;
- BufferedReader buff = new BufferedReader(new FileReader(FileName));
- StrSrc = buff.readLine();
- do {
- System.out.println(StrSrc);
- if (isStrCorrect(StrSrc)) {
- if (Proc(StrSrc)) {
- System.out.println("Brackets agreed.");
- }
- else {
- System.out.println("Brackets are not agreed.");
- }
- }
- else {
- System.out.println("There are no brackets in the line!");
- }
- StrSrc = buff.readLine();
- }
- while (StrSrc != null);
- buff.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement