Created
August 3, 2015 07:21
-
-
Save pieman72/3e17b127849d3454f24e to your computer and use it in GitHub Desktop.
A quick java program to check proper matching of braces in a file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
public class CheckBraces{ | |
// Print errors and set exit status | |
public static void die(String msg){ | |
System.err.println(msg); | |
System.exit(1); | |
} | |
// Process a file named with a CLI arg | |
public static void main(String[] args){ | |
// Check inputs | |
if (args.length < 1) CheckBraces.die("No file provided to check."); | |
BufferedReader reader = null; | |
try{ reader = new BufferedReader(new FileReader(args[0])); } | |
catch(Exception e){ die("Could not open file '" + args[0] + "'."); } | |
// Set up variables | |
String braces = "{}[]()"; | |
int len = 0; | |
int index = -1; | |
int lastIndex = -1; | |
int stackEnd = 0; | |
int MAX_READ = 1024; | |
int MAX_STACK = 128; | |
char[] buf = new char[MAX_READ]; | |
char[] stack = new char[MAX_STACK]; | |
// Read input from file | |
while(true){ | |
try { len = reader.read(buf, 0, MAX_READ); } | |
catch(Exception e){ die("Error reading file '" + args[0] + "'."); } | |
if (len < 1) break; | |
// Check read characters for braces | |
for(int i=0; i<len; ++i){ | |
int temp = braces.indexOf(buf[i]); | |
if(temp == -1) continue; | |
index = temp; | |
// Open braces | |
if(index%2 == 0){ | |
stack[stackEnd++] = buf[i]; | |
lastIndex = index; | |
// Close braces | |
}else{ | |
if(stackEnd <= 0) die("Found close '" + buf[i] + "' with no open '" + braces.charAt(index - 1) + "'."); | |
if(index-lastIndex != 1) die("Found '" + buf[i] + "' when expecting '" + braces.charAt(lastIndex + 1) + "'."); | |
if(--stackEnd == 0){ | |
lastIndex = -1; | |
}else{ | |
lastIndex = braces.indexOf(stack[stackEnd-1]); | |
} | |
} | |
} | |
} | |
// Final check | |
if (stackEnd > 0) die("End of file while still expecting '" + braces.charAt(lastIndex + 1) + "'."); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment