java - Recursion and Iteration method to locate missing brackets -


for assignment, specification simple. given text file of arbitrary length (possibly thousands of characters). considered correct, must contain matching pairs of brackets { }, [ ], , ( ). bracket pairs may nested arbitrary depth (but not need worry stack overflow) arbitrary amounts of text between brackets. file contains no brackets trivially correct. when discover pair of mismatched brackets, must report brackets , index in file. first character in file index 0. example, if file contains file has open { , { followed ) , } , text. program should report mismatch because { @ index 36 closed ) @ index 50. can think of start of file super opening bracket not match closing bracket. if file contains many closing brackets, mismatched opening bracket start of file. should use string stx (old ascii start of text) report this. example, closing ] has no matching open [. in case, program should report mismatch because stx @ index -1 closed ] @ index 13. similarly, can think of end of file super closing bracket not match opening bracket. file may contain many open brackets. report if mismatched closing bracket (nonexistent) close bracket after end of file. example open ( has no match reoprt mismatch because ( @ index 10 closed eof @ index 24. task write 2 methods, recursive method, recursivematch , , iterative method, iterativematch , process file , check if brackets match. when either method detects bracket mismatch, should throw exception of class matchfail. information in matchfail object should include mismatched brackets , indices in file.

here code have far:

import java.io.file ; import java.io.filereader ; import java.io.ioexception ;  /** * development driver assignment #4, matching brackets.  *   * @author lou  * @param args[0]  *            name of file check  */ public class assign4 {   public static void main(string[] args) { /*  * check user has supplied file name, , file  * exists , readable.  */ if (args.length <= 0) {   system.out.println("usage: java assign4 <filename>") ;   system.exit(1) ; } string filename = args[0] ; file handle = new file(filename) ; if (!(handle.exists() && handle.canread())) {   system.out.println("please check file \"" + filename       + "\" exists , readable.") ;   system.exit(2) ; } /*  * create input stream of type filereader read file character  * character. can throw (checked) ioexception need  * wrap in try/catch block.  *  * it's practice close filereader avoid  * resource leak (resources allocated not released). if  * src not null, resources may have been allocated if creation of  * filereader fails , should attempt close free them.  * closing file reader can throw ioexception, need  * nested try/catch block.  */ filereader src = null ; try {   src = new filereader(handle) ; } catch (ioexception ex) {   system.out.println("exception while opening file \"" +       filename + "\" read.") ;   system.out.println("exception: " + ex) ;   try { if (src != null) src.close() ;   } catch (ioexception closeex) { system.out.println(     "exception while closing file \"" + filename + "\".") ; system.out.println("exception: " + closeex) ;   }   system.exit(3) ; } /*  * try recursive match method first. matchfail exception  * possibility. allow other exceptions might thrown  * don't attempt anything.  */ matchbrackets matcher = new matchbrackets() ; try {   matcher.recursivematch(src) ;   system.out.println("brackets match (recursive)!") ; } catch (matchfail ex) {   system.out.println("a bracket on own no good!") ;   system.out.println(ex) ; } catch (exception ex) {   system.out.println("unexpected exception "+ex) ; } /*  * need return beginning of file test iterative  * match. filereader, requires closing , reopening file.  */ try {   system.out.println("attempting close , reopen.") ;   src.close() ;   src = new filereader(handle) ; } catch (ioexception ex) {   system.out.println("exception while reopening file \"" + filename   + "\" read.") ;   system.out.println("exception: " + ex) ;   try { if (src != null) src.close() ;   } catch (ioexception closeex) { system.out.println(     "exception while closing file \"" + filename + "\".") ; system.out.println("exception: " + closeex) ;   }   system.exit(3) ; } /*  * try iterative match method.  */ try {   matcher.iterativematch(src) ;   system.out.println("brackets match (iterative)!") ; } catch (matchfail ex) {   system.out.println("a bracket on own no good!") ;   system.out.println(ex) ; } catch (exception ex) {   system.out.println("unexpected exception "+ex) ; } /*  * close file , we're done.  */ try {   src.close() ; } catch (ioexception ex) {   system.out.println(       "exception while closing file \"" + filename + "\".") ;   system.out.println("exception: " + ex) ;   system.exit(3) ; } return ; } } 

and

import java.io.filereader ; import java.io.ioexception ; import java.util.arraydeque ;  /**   skeleton matchbrackets class. */ public class matchbrackets {    /**    * make constant it's clear we're recognising end-of-file.    */   private final int eof = -1 ;    /**    * helper method encapsulate activity of reading    * character.    *     * filereader class uses common convention in character i/o:    * return each character int; allows value -1    * used indicate eof. little helper routine hides    * try/catch statement that's required handle possibility    * filereader.read might throw ioexception.    *     * @param source    *        source of characters    * @return eof on end-of-file or exception, or single character    *         (as int)    */   private int getonechar (filereader source)   {     int charasint = eof ;    try {   charasint = source.read() ;     } catch (ioexception ex) {    system.out.println("exception: " + ex) ;   charasint = eof ;    }    return (charasint) ;   }  /**  * recursive method match brackets.  *   * @param src  *        source of characters  */ public void recursivematch (filereader src)        throws matchfail  { /*   must write proper body recursivematch. bit of code below   show how use getonechar , throw exception. */ int charasint = getonechar(src) ; if (charasint != eof) {   char firstchar = (char) charasint ;   system.out.println(       "the first character of file '" + firstchar + "'.") ; } else {   system.out.println("this file empty!") ; } throw new matchfail("you must write recursivematch!",42,             character.tostring('}'),42) ; }  /**  * iterative method match brackets.  *   * @param src  *        source of characters  */ public void iterativematch (filereader src) throws matchfail {   /*     must write proper body method, too.   */   throw new matchfail() ; }  } 

and

/**  exception class use bracket matching methods.  <p>  when bracket mismatch detected, exception object should  created, loaded information mismatched pair of brackets, ,  thrown.  </p><p>  information provided should include opening bracket , index in  file, , closing bracket , index in file.  file containing k characters, character indices range 0 k-1.  definition,  <ul>  <li> `character' before start of file has index -1 ,  represented string "stx" (start of text).</li>  <li> `character' after end of file has index k ,      represented string "eof" (end of file).</li>  </ul>  </p><p>  matchfail subclassed exception, hence checkable exception  , methods might throw matchfail must declare exception  throws clause.   */   public class matchfail extends exception  {  /** index of opening bracket of mismatched pair. */ private int openndx ;  /** string representation of opening bracket of mismatched pair. */ private string openbkt ;  /** index of closing bracket of mismatched pair. */ private int closendx ;  /** string representation of opening bracket of mismatched pair. */ private string closebkt ;  /** convenience constructor set attributes. */ public matchfail (string openbkt, int openndx,         string closebkt, int closendx) { this.openbkt = openbkt ; this.openndx = openndx ; this.closebkt = closebkt ; this.closendx = closendx ; }  /** constructor. <p> initialise attributes values invalid it's easy detect algorithm errors. </p> */ public matchfail () {   this("invalid",-10,"invalid",-10) ; }  /** retrieve opening bracket. */ public string getopenbkt () { return (openbkt) ; }  /** retrieve index of opening bracket. */ public int getopenindex () { return (openndx) ; }  /** retrieve closing bracket. */ public string getclosebkt () { return (closebkt) ; }  /** retrieve index of opening bracket. */ public int getcloseindex () { return (closendx) ; }  /** set opening bracket. */ public void setopenbkt (string openbkt) { this.openbkt = openbkt ; }  /** set index of opening bracket. */ public void setopenindex (int openndx) { this.openndx = openndx ; }  /** set closing bracket. */ public void setclosebkt (string closebkt) { this.closebkt = closebkt ; }  /** set index of closing bracket. */ public void setcloseindex (int closendx) { this.closendx = closendx ; }  /** return string representation of exception. */ public string tostring () {   string rep = "'"+openbkt+"' @ index "+openndx+" matched '" +          closebkt+"' @ index "+closendx ;    return (rep) ; }  } 

the problem having in creating recursive , iterator method in order find brackets , report index missing bracket located. don't understand how supposed this. @ appreciated! thank you.

as parse document create new 1 of these every time run starter , add them stack current counter loop variable value.

public class bracket {     int location;     char bracket;      public bracket(int loc, char b) {         location = loc;         bracket = b;     }      public char getbracket() { return bracket; }             public int getloc() { return location; }      public static boolean isstarter(char b) {         return b == '(' || b == '{'; // || etc....     }      public boolean equals(bracket other) {         return bracket == other.getbracket();     }      public char getmatching() {         switch(bracket) {             case '(': return ')';             // on , forth         }     }      public boolean matches(char other) {       return (getmatching() == other);     } } 

then, in code: stack stack = new stack<>();

// in loop if (bracket.isstarter(currentcharacter)) {   stack.push(new bracket(currentlocation, currentcharacter)); } else {    if (stack.peek().matches(currentcharacter))      stack.pop();    else {      bracket b = stack.pop();      system.out.println("mismatch error " + b.getbracket() +         " @ character position " + b.getloc() +         " followed " + currentcharacter +         " @ position " + currentposition + ".");    } } // on order @ least 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -