Solved

Delimeter Check

Posted on 2003-10-24
11
362 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 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
 
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

707 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now