How to validate and parse valid parenthesis and invalidate nested parenthesis string .


 


In this  Java code, we will learn to validate and parse a parenthesis contained sting as well as invalidate nested parenthesis string for parse.

 First, we will take a string from the command line then read it. Then we will check either it valid parenthesis string or not. The code is below.



    

import java.util.*


public class NestedPranthesisCheck{

    public static void main(String args[]) {

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a string:");

        String str = in.nextLine();

        str = str.toUpperCase();

        int len = str.length();

        

        StringBuffer sb = new StringBuffer();

        

        int open = -1;  //Contains index of opening parenthesis

        

        for (int i = 0; i < len; i++) {

            char ch = str.charAt(i);

            if (ch == '(') {

                if (open != -1) {

                    System.out.println("Sorry, an invalid string");

                    return;

                }

                

                open = i;

            }

            

            if (open == -1) {

                sb.append(ch);

            }

            

            if (ch == ')') {

                if (open == -1) {

                    System.out.println("Sorry, an invalid string");

                    return;

                }

                

                open = -1;

            }

            

            

        }

        

        /*

         * Using StringTokenizer to remove 

         * extra spaces between words

         */

        

        StringTokenizer st = new StringTokenizer(sb.toString());

        while (st.hasMoreTokens()) {

            System.out.print(st.nextToken());

            System.out.print(" ");

        }


    }

}


 Now when test this code 


Enter a string:

you ( name (is) ) Mukesh 

Sorry, an invalid string


Enter a string:

your name (is)  (Mukesh.) 

YOUR NAME 


Enter a string:

your name (is)  Mukesh.

YOUR NAME MUKESH. 


 

          

      

How to validate and parse valid parenthesis and invalidate nested parenthesis string . How to validate and parse valid parenthesis and invalidate nested parenthesis string .  Reviewed by Mukesh Jha on 3:24 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.