Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.LinkedList;
- import java.util.Scanner;
- public class CheckBalanced {
- /**
- * Program: CheckBalanced.java
- * Purpose: Read a Java source code file and check it has balanced brackets{}.
- * Creator: Chris Clarke, author "50 Java Program Source Codes" (in paperback and e-book)
- * - and now also by Chris Clarke: "50 More Java Source Codes".
- * Created: 31.10.2014
- */
- // create linked list object as instance variable
- LinkedList<Integer> list = new LinkedList<Integer>();
- // initialise top (of stack)
- static int top = -1;
- public void push(int t) {
- list.add(new Integer(++t));
- } // push()
- public int pop() {
- if (top != -1)
- return list.remove(top--);
- return top;
- } // pop()
- public static void main(String[] args) {
- if (args.length==0) {
- System.out.println("Usage: java CheckBalanced \"MyProgram.java\"");
- return;
- } // if
- File f;
- Scanner scan = null;
- String line;
- char ch;
- CheckBalanced stack = new CheckBalanced();
- try {
- f = new File(args[0]);
- scan = new Scanner(f);
- } catch (IOException e) {
- System.out.println("Caught IOException");
- return;
- } // try
- while (scan.hasNextLine()) {
- line = scan.nextLine();
- for (int i=0; i<line.length(); i++) {
- ch = line.charAt(i);
- if (ch=='{')
- stack.push(top);
- if (ch=='}')
- top = stack.pop();
- } // for
- } // while
- if (scan!=null) scan.close();
- if (top == -1)
- System.out.println("BALANCED");
- else
- System.out.println("NOT BALANCED");
- } // main()
- } // class CheckBalanced
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement