Solved

Delimeter Check

Posted on 2003-10-24
11
367 Views
Last Modified: 2012-05-04
I need help with this:

Write a class method named 'DelimMatch' and a method main that will test it

The method 'match' will take a String that may contain any number of parentheses, brackets, or braces as a parameter and return true if the parentheses, brackets, or braces are balanced and false if they are not.

It is giving one error and I need help setting it up for braces as well(I have brackets and parentheses already)

import java.io.*;
import java.util.Stack;

public class DelimMatch
{
    public static void main (String [] args) throws java.io.IOException
    {
        System.out.println("Enter expression: ");
      BufferedReader d = new BufferedReader(new InputStreamReader(System.in));
      String line = d.readLine();

        Stack parens = new Stack();
      
        for (int i = 0; i < line.length(); i++)
        {
            if (line.charAt(i) == '(' || line.charAt(i) == '[')
            {
                parens.push(new Character(line.charAt(i)));
            }
            else if (line.charAt(i) == ')' || line.charAt(i) == ']')
            {
            if (parens.empty())
                {
                    System.out.println("Error: unmatched right delimeter at index " + i);
                    return;
            }
            else
                {
                    Character top = (Character)parens.pop();
                    if (!match(top.charValue(), line.CharAt(i)))
                    {
                        System.out.println("Error: mismatched delimeters at index " + i);
                  return;
                    }
            }
            }
      }
      if (!parens.empty())
        {
            System.out.println("Error: unclosed left delimeter");
      }
      else
        {
            System.out.println("Expression is OK");
      }
    }
      
    private static boolean match(char ch1, char ch2)
    {
        return ((ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2 == ']'));
    }
}


help please

rbg
0
Comment
Question by:rbgerman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 5
11 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 9617890
What about nesting?
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9618298
>>It is giving one error

what is the error?
0
 
LVL 5

Accepted Solution

by:
lwinkenb earned 50 total points
ID: 9618315
hmm.. I copied you code, and changed
if (!match(top.charValue(), line.CharAt(i)))
to
if (!match(top.charValue(), line.charAt(i))) // notice the lower case 'c'

Now it seems to work just fine.  To add braces, just do it the same way you do brackets and parenthesis:
 if (line.charAt(i) == '(' || line.charAt(i) == '[' || line.charAt(i) == '{')

You should be able to get it from there.  If not, post where you are still having trouble.
0
What Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

 
LVL 1

Author Comment

by:rbgerman
ID: 9629684
hey thanks...can't believe I missed that.  I stared at it for an our wondering why that charAt was giving me fits (damn case sensitivity).  I will award the points to you..can you help with one thing though.  I have slightly changed the code...but now I would really like a while loop to allow the user to enter as many expressions or Strings as they want.  Could you help me do that please?

Here is the modified code:

import java.util.Stack;
import TerminalIO.KeyboardReader;

public class DelimMatch
{
    public static void main (String [] args)
    {
        KeyboardReader reader = new KeyboardReader();
       
        String line = reader.readLine("Enter expression: ");

        Stack parens = new Stack();
      
        for (int i = 0; i < line.length(); i++)
        {
            if (line.charAt(i) == '(' || line.charAt(i) == '[')
            {
                parens.push(new Character(line.charAt(i)));
            }
            else if (line.charAt(i) == ')' || line.charAt(i) == ']')
            {
            if (parens.empty())
                {
                    System.out.println("Error: unmatched right delimeter at index " + i);
                    return;
            }
            else
                {
                    Character top = (Character)parens.pop();
                    if (!checkDelimeters(top.charValue(), line.charAt(i)))
                    {
                        System.out.println("Error: mismatched delimeters at index " + i);
                  return;
                    }
            }
            }
      }
      if (!parens.empty())
        {
            System.out.println("Error: unclosed left delimeter");
      }
      else
        {
            System.out.println("Expression is OK");
      }
       
    }
      
    private static boolean checkDelimeters(char ch1, char ch2)
    {
        return ((ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2 == ']'));
    }
}


thanks

rbg
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9630588
just place a while loop around the code in the main method:

import java.util.Stack;
import TerminalIO.KeyboardReader;

public class DelimMatch
{
    public static void main (String [] args)
    {
        while(true) {
              KeyboardReader reader = new KeyboardReader();
              
              String line = reader.readLine("Enter expression: ");
      
              Stack parens = new Stack();
          
              for (int i = 0; i < line.length(); i++)
              {
                  if (line.charAt(i) == '(' || line.charAt(i) == '[')
                  {
                      parens.push(new Character(line.charAt(i)));
                  }
                  else if (line.charAt(i) == ')' || line.charAt(i) == ']')
                  {
                            if (parens.empty())
                      {
                          System.out.println("Error: unmatched right delimeter at index " + i);
                          return;
                            }
                            else
                      {
                          Character top = (Character)parens.pop();
                          if (!checkDelimeters(top.charValue(), line.charAt(i)))
                          {
                              System.out.println("Error: mismatched delimeters at index " + i);
                                       return;
                          }
                            }
                  }
                 }
                   if (!parens.empty())
                     {
                         System.out.println("Error: unclosed left delimeter");
                     }
                    else
                    {
                        System.out.println("Expression is OK");
                    }
            }  
    }
     
    private static boolean checkDelimeters(char ch1, char ch2)
    {
        return ((ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2 == ']'));
    }
}
0
 
LVL 1

Author Comment

by:rbgerman
ID: 9634246
i guess what i am asking is ...
how can i set it up to start out with...

"do you want to enter another expression? (Y or N)"
Y
enter it

answer

"do you want to enter another expression? (Y or N)"
N
exit

please help me out...i am confused a bit

rbg
0
 
LVL 1

Author Comment

by:rbgerman
ID: 9634379
i went ahead and awarded you then points before i forgot....

the while loop does work...but I needed some guidance in making it ask:

"do you want to enter another expression? (Y or N)"

so it will exit

please help me out here

rbg
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9635284
change it to this:

boolean loop = true;

while(loop) {
  //The delim code goes here
  System.out.println("do you want to enter another expression? (Y or N)");
  String res = //user input
  if(!res.ignoreCase.equals("y"))
    loop = false;
}
0
 
LVL 1

Author Comment

by:rbgerman
ID: 9637076
thanks man...awesome

i see how that is set up now

rbg
0
 
LVL 1

Author Comment

by:rbgerman
ID: 9637733
it's actually still not looping...

if i type Y or y it still ends???  here is the final code with the loop additions...hope you still want to help

import java.util.Stack;
import TerminalIO.KeyboardReader;

public class DelimeterCheck
{
    public static void main (String [] args)
    {
        boolean loop = true;
       
        while (loop)
        {        
        KeyboardReader reader = new KeyboardReader();      
        String line = reader.readLine("Enter expression: ");
        Stack parens = new Stack();
      
        for (int i = 0; i < line.length(); i++)
        {
            if (line.charAt(i) == '(' || line.charAt(i) == '[' || line.charAt(i) == '{')
            {
                parens.push(new Character(line.charAt(i)));
            }
            else if (line.charAt(i) == ')' || line.charAt(i) == ']' || line.charAt(i) == '}')
            {
            if (parens.empty())
                {
                    System.out.println("Error: unmatched right delimeter at index " + i);
                    return;
            }
            else
                {
                    Character top = (Character)parens.pop();
                    if (!checkDelimeters(top.charValue(), line.charAt(i)))
                    {
                        System.out.println("Error: mismatched delimeters at index " + i);
                  return;
                    }
            }
            }
      }
      if (!parens.empty())
        {
            System.out.println("Error: unclosed left delimeter");
      }
      else
        {
            System.out.println("Expression is OK");
      }          
       
        System.out.println("Do you want to enter another expression? (Y or N)");
        String res = reader.readLine();
        if(!res.equals("y") || !res.equals("Y")) loop = false;        
        }
    }
      
    private static boolean checkDelimeters(char ch1, char ch2)
    {
        return ((ch1 == '(' && ch2 == ')') || (ch1 == '[' && ch2 == ']') || (ch1 == '{' && ch2 == '}'));
    }
}

rbg
0
 
LVL 5

Expert Comment

by:lwinkenb
ID: 9637854
>>if(!res.equals("y") || !res.equals("Y"))
That conditional statement will ALWAYS return true.  It should be:
if(!res.equals("y") && !res.equals("Y"))
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question