Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- /**
- * Grouping symbols checking program / Homework 2
- *
- * @author Jose Ed. Dieck
- * @version 1/30/2015
- *
- */
- public class Homework2 {
- private Homework2() {
- }
- /**
- * First spot on args data
- */
- public static final int FILEPATH = 0;
- /**
- * Default value for an empty args length
- */
- public static final int EMPTY_ARGS = 0;
- /**
- * Default count start variable
- */
- public static final int COUNT_START = 0;
- /**
- * String variable containing opening grouping symbols for comparison
- */
- public static final String OPENING = "({[";
- /**
- * String variable containing closing grouping symbols for comparison
- */
- public static final String CLOSING = ")}]";
- /**
- * Main method for the program, taking in a file path as argument
- *
- * @param args
- * filepath for the file to be checked
- * @throws FileNotFoundException
- * exception thrown if the file could not be found
- */
- public static void main(String[] args) throws FileNotFoundException {
- if (args.length == EMPTY_ARGS) {
- System.out.println("Usage: java Homework2 (file path)");
- return;
- }
- File toRead = new File(args[FILEPATH]);
- boolean checked = checkBraces(toRead);
- if (checked) {
- System.out.println("The file is valid.");
- } else {
- System.out.println("The file is not valid.");
- }
- }
- public static boolean checkBraces(File file) throws FileNotFoundException {
- Scanner read = new Scanner(file);
- Stack<String> openChar = new Stack<String>();
- String line = "";
- String toCheck = "";
- while (read.hasNextLine()) {
- line = read.nextLine();
- for (int i = COUNT_START; i < line.length(); i++) {
- toCheck = Character.toString(line.charAt(i));
- if (OPENING.contains(toCheck)) {
- openChar.push(toCheck);
- } else if (CLOSING.contains(toCheck)) {
- if (openChar.isEmpty()) {
- read.close();
- return false;
- } else if (toCheck.equals(")")) {
- if (openChar.peek().equals("(")) {
- openChar.pop();
- } else {
- read.close();
- return false;
- }
- } else if (toCheck.equals("}")) {
- if (openChar.peek().equals("{")) {
- openChar.pop();
- } else {
- read.close();
- return false;
- }
- } else {
- if (openChar.peek().equals("[")) {
- openChar.pop();
- } else {
- read.close();
- return false;
- }
- }
- }
- }
- }
- read.close();
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement