?
Solved

Delimeter Check

Posted on 2003-10-24
11
Medium Priority
?
374 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
  • 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 200 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
This video teaches viewers about errors in exception handling.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month13 days, 14 hours left to enroll

809 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