?
Solved

Delimeter Check

Posted on 2003-10-24
11
Medium Priority
?
369 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 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
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 learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Suggested Courses
Course of the Month14 days, 22 hours left to enroll

770 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