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 CheckBalanced2 {
- /**
- * Program: CheckBalanced2.java
- * Purpose: Read a Java source code file and check it has balanced brackets {}()[].
- * Do not include brackets within quotes or comments.
- * Creator: Chris Clarke
- * Created: 13.11.2015
- */
- // 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 doBalanceCheck(char ch0, char ch1, CheckBalanced2 stack, String javaSource) {
- File f;
- Scanner scan = null;
- String line;
- char ch;
- int lineNum = 0;
- int openLineNum = 0;
- int position = 0;
- top = -1;
- boolean inSingleQuotes = false;
- boolean inDoubleQuotes = false;
- boolean inMultiLineComment = false;
- System.out.printf("%c %c: ", ch0, ch1);
- try {
- f = new File(javaSource);
- 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=='\"') {
- inDoubleQuotes = !inDoubleQuotes;
- } else if (ch=='\'') {
- inSingleQuotes = !inSingleQuotes;
- } else if (ch=='/' && i<line.length()-1) {
- if (line.charAt(i+1)=='/') {
- break; // ignore rest of line
- } else if (line.charAt(i+1)=='*') {
- inMultiLineComment = true;
- }
- } else if (ch=='*' && i<line.length()-1) {
- if (line.charAt(i+1)=='/') {
- inMultiLineComment = false;
- }
- }
- if (!inDoubleQuotes && !inSingleQuotes && !inMultiLineComment) {
- if (ch==ch0) {
- stack.push(++top);
- openLineNum = lineNum;
- position = i;
- }
- if (ch==ch1) {
- stack.pop();
- top--;
- }
- } // if
- } // for
- lineNum++;
- } // while
- if (scan!=null) scan.close();
- if (top == -1) System.out.printf("BALANCED%n");
- else System.out.printf("NOT BALANCED at line %d, position %d%n", openLineNum+1, position+1);
- } // doBalanceCheck()
- public static void main(String[] args) {
- CheckBalanced2 myStack = new CheckBalanced2();
- if (args.length==0) {
- System.out.println("Usage: java CheckBalanced2 \"MyProgram.java\"");
- } else {
- myStack.doBalanceCheck('{', '}', myStack, args[0]);
- myStack.doBalanceCheck('(', ')', myStack, args[0]);
- myStack.doBalanceCheck('[', ']', myStack, args[0]);
- } // if
- } // main()
- } // class CheckBalanced2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement