Stack application: Separator matching problem-write a program to determine whether the delimiters in the Java statement match

Source: Internet
Author: User

Delimiter matching problem: Write a program that determines whether the delimiters in a Java statement match.

A delimiter and its matching delimiter can be separated by other delimiters, that is, the delimiter allows nesting, so a delimiter can be matched only if all the right delimiters in front of it are matched.
For example, a conditional statement: if (i!= (n[8] +1)), the first opening parenthesis must match the last closing parenthesis, but this can only be done if the second opening parenthesis matches the penultimate right parenthesis. , and the second bracket matches only after the third opening parenthesis matches the third closing bracket.
Visible, the first occurrence of the left delimiter in order to be matched at the end, this processing and stack structure of the advanced characteristics of the back of the match.

The separator matching algorithm is as follows:
Scans the Java statements from left to right, reading the characters constantly from the statement, read one character at a time, if it is found to be a separator, press it into the stack, and when the first right separator is read from the input, then the left separator on top of the stack pops up and determines if it matches the right delimiter, if it does not match, the match fails, and the program complains If there is no left delimiter in the stack that matches the right delimiter (that is, the stack is empty), or there has been no matching left delimiter, the left delimiter is not matched, the performance of all elements are read, the stack still has a separator, the match fails, the program error; if all the characters read in the end, the stack is empty, then the match is successful.

Package com.stacktest;

Import Java.util.Scanner;

Import javax.swing.text.AbstractDocument.LeafElement;  public class Separator {private final int left = 0;
    The record delimiter is the "left" separator private final int right=1;   Private final int other = 2; Record the type of other character//judgment separator, there are three illegal public int verifyflag (String str) {if ("("). Equals (str) | | [". Equals (str) | |" {". Equals (str) | |"
        /* ". Equals (str)) {return left; else if (")". Equals (str) | | "]". Equals (str) | | "}". Equals (str) | |
        "*/". Equals (str)) {return right; 
        else {return other; }///Match left delimiter str1 and right delimiter str2 match public boolean matches (String str1,string str2) {if (("(). E Quals (STR1) && ")". Equals (str2)) | | ("[". Equals (STR1) && "]". Equals (str2) | | ("{". Equals (STR1) && "}". Equals (str2) | | ("/*". Equals (STR1) && "* *". Equals (STR2)) {return true;
        else {return false; } Private Boolean Islegal (String str) throws Exception {if (!).  Equals (str) && str!= null) {sqstack s=new sqstack (100);
            New sequential stack int length=str.length (); for (int i = 0; i < length; i++) {char c=str.charat (i);//specify indexed char value str

                ing t=string.valueof (c);
                            if (i!= length) {if (('/' = = C && ' * ' = = Str.charat (i+1)) | |
                    (' * ' = = c && '/' = = Str.charat (i+1))]
                        {T=t.concat (string.valueof (Str.charat (i+1)));
                    ++i;   } if (left = = Verifyflag (t)) {S.push (t);
    Press into Stack}            else if (right = = Verifyflag (t)) {if (S.isempty () | |!matches (S.POP (). tostr
                    ing (), t)) {throw new Exception ("ERROR: Invalid Java statement"); }} if (!s.isempty ()) {throw new Exception ("Error: JA



            VA Grammar not valid ");

        return true;
    else throw new Exception ("Error: Java statement is empty");
        public static void Main (string[] args) throws Exception {Separator se=new Separator ();
        System.out.println ("Please enter Java statement");
        Scanner sc=new Scanner (system.in);
        if (Se.islegal (Sc.nextline ())) {System.out.println ("Java statement valid");
        else {System.out.println ("error, Java statement not valid");


 }
    }


}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.