Advertisement
brilliant_moves

CheckBalanced.java

Oct 31st, 2014
439
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.59 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.LinkedList;
  3. import java.util.Scanner;
  4.  
  5. public class CheckBalanced {
  6.  
  7.     /**
  8.     *   Program: CheckBalanced.java
  9.     *   Purpose: Read a Java source code file and check it has balanced brackets{}.
  10.     *   Creator: Chris Clarke, author "50 Java Program Source Codes" (in paperback and e-book)
  11.     *        - and now also by Chris Clarke: "50 More Java Source Codes".
  12.     *   Created: 31.10.2014
  13.     */ 
  14.  
  15.     // create linked list object as instance variable
  16.     LinkedList<Integer> list = new LinkedList<Integer>();
  17.  
  18.     // initialise top (of stack)
  19.     static int top = -1;
  20.  
  21.     public void push(int t) {
  22.         list.add(new Integer(++t));
  23.     } // push()
  24.  
  25.     public int pop() {
  26.         if (top != -1)
  27.             return list.remove(top--);
  28.         return top;
  29.     } // pop()
  30.  
  31.     public static void main(String[] args) {
  32.         if (args.length==0) {
  33.             System.out.println("Usage: java CheckBalanced \"MyProgram.java\"");
  34.             return;
  35.         } // if
  36.  
  37.         File f;
  38.         Scanner scan = null;
  39.         String line;
  40.         char ch;
  41.  
  42.         CheckBalanced stack = new CheckBalanced();
  43.  
  44.         try {
  45.             f = new File(args[0]);
  46.             scan = new Scanner(f);
  47.         } catch (IOException e) {
  48.             System.out.println("Caught IOException");
  49.             return;
  50.         } // try
  51.  
  52.         while (scan.hasNextLine()) {
  53.             line = scan.nextLine();
  54.             for (int i=0; i<line.length(); i++) {
  55.                 ch = line.charAt(i);
  56.                 if (ch=='{')
  57.                     stack.push(top);
  58.  
  59.                 if (ch=='}')
  60.                     top = stack.pop();
  61.  
  62.             } // for
  63.         } // while
  64.  
  65.         if (scan!=null) scan.close();
  66.  
  67.         if (top == -1)
  68.             System.out.println("BALANCED");
  69.         else
  70.             System.out.println("NOT BALANCED");
  71.  
  72.     } // main()
  73.  
  74. } // class CheckBalanced
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement