Solved

Delimeter Check

Posted on 2003-10-24
11
364 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
The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
groupSum6 challenge 6 86
micro services vs rest web services 16 107
Java Loop 6 62
split string containing \r\n in Java 46 44
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
The viewer will learn how to implement Singleton Design Pattern in Java.

832 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