Question

In: Computer Science

WRITE IN JAVA PLEASE~ A string may use more than one type of delimiter to bracket...

WRITE IN JAVA PLEASE~

A string may use more than one type of delimiter to bracket information into "blocks". The primary ways to divide things up into block is by the braces { } , parentheses ( ), and brackets [ ] as delimiters.

  • A string is considered properly delimited if each right delimiter ] } or )( is matched with a preceding left delimiter { [ ( of the same type in such a way that either the resulting blocks of information are disjoint or one of them is contained nested within the other.  
  • Write a method that accepts a string in as a parameter and returns back a boolean value determining if the string is properly delimited.
  • Read the string char by char, ignoring all symbols but the [,{,(,},)]. Symbols.
    • if it is an open delimiter add it to the stack
    • if it is a close delimiter check two things
      • is the stack empty?
      • is the top of the stack the correct open type.
  • At the end of the string, if you haven't already returned an answer
    • Check that the stack is empty.
  • Use a single stack to check whether a string containing brackets is or is not properly delimited.
  • Test your method on the following strings:
  • String string1 = "[{}]";
    • good
  • String string2 = "[x{12345}xxx]xxx";
    • good
  • String string3 = "[1{2(3)4}5]";
    • good
  • String string4 = "[][](){}";
    • good
  • String string5 = "[[]}";
    • bad
  • String string6 = "[])";
    • bad
  • String string7 = "[]123{}123()123[{}]";
    • good
  • String string8 = "[[[[[]]]]]((((())))){{{{{{{{{{[]}}}}}}}}}}";
    • good
  • String string9 = "[[[[[]]]]]((((())))){{{{{{{{{{[]}}}}}}}}]}";
    • bad
  • String string10 = "[{({({({([[]])})})})}][{}]{}{{}}";
    • good
  • String string11 = "[{(";
    • bad
  • String math = "2+(3+5*(5+7-4)*[1+2+3+(6/5)])/(2*a)";
    • good

Solutions

Expert Solution

CODE:

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

public class CheckParanthesis {
public static boolean checkbalance(String str)
{
//Defining a stack.
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<str.length();i++)
{
//taking each character at a time.
char ch=str.charAt(i);
//if the character is anything other than delimiters, we will ignore it.
if(ch!='(' && ch!='[' && ch!='{' && ch!=')' && ch!=']' && ch!='}')
continue;
//if the character is an open delimiter we push it in the stack.
if(ch=='(' || ch=='[' || ch=='{')
{
stack.push(ch);
continue;
}
//If its not an opening delimiter or a character, it must be a closing delimiter. And so, there must be an opening delimeter in the stack.
if(stack.isEmpty())
return false;//if the stack is empty, then there is no opening delimiter and therefore it is an invalid expression.
if(ch==')' || ch==']' || ch=='}')//if the character is a closing delimter.
{
char x=stack.pop();//pop the last entered stack value. or the value in the top of the stack
//if they dont match we return false.
if(ch=='}' && x!='{')
return false;
if(ch==')' && x!='(')
return false;
if(ch==']' && x!='[')
return false;
}
}
return stack.isEmpty();//if the stack is not empty it will return false, else true.
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter a String: ");
String str=in.nextLine();
if(checkbalance(str))
{
System.out.println("good");
}
else
{
System.out.println("bad");
}
}
}

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

public class CheckParanthesis {
    public static boolean checkbalance(String str)
    {
        //Defining a stack.
        Stack<Character> stack = new Stack<Character>();
        for(int i=0;i<str.length();i++)
        {
            //taking each character at a time.
            char ch=str.charAt(i);
            //if the character is anything other than delimiters, we will ignore it. 
            if(ch!='(' && ch!='[' && ch!='{' && ch!=')' && ch!=']' && ch!='}')
                continue;
            //if the character is an open delimiter we push it in the stack.
            if(ch=='(' || ch=='[' || ch=='{')
            {
                stack.push(ch);
                continue;
            }
            //If its not an opening delimiter or a character, it must be a closing delimiter. And so, there must be an opening delimeter in the stack.
            if(stack.isEmpty())
                return false;//if the stack is empty, then there is no opening delimiter and therefore it is an invalid expression. 
            if(ch==')' || ch==']' || ch=='}')//if the character is a closing delimter.
            {
                char x=stack.pop();//pop the last entered stack value. or the value in the top of the stack
                //if they dont match we return false.
                if(ch=='}' && x!='{')
                    return false;
                if(ch==')' && x!='(')
                    return false;
                if(ch==']' && x!='[')
                    return false;
            }
        }
        return stack.isEmpty();//if the stack is not empty it will return false, else true.
    }
    public static void main(String[] args)
    {
        Scanner in=new Scanner(System.in);
        System.out.println("Enter a String: ");
        String str=in.nextLine();
        if(checkbalance(str))
        {
            System.out.println("good");
        }
        else
        {
            System.out.println("bad");
        }
    }
}

OUTPUT:

If you have any doubts or require any clarifications, please leave a comment and i will answer it. Thank you :)


Related Solutions

JAVA question A string may use more than one type of delimiter to bracket information into...
JAVA question A string may use more than one type of delimiter to bracket information into "blocks". The primary ways to divide things up into block is by the braces { } , parentheses ( ), and brackets [ ] as delimiters. A string is considered properly delimited if each right delimiter ] } or )( is matched with a preceding left delimiter { [ ( of the same type in such a way that either the resulting blocks of...
JAVA JAVA JAVA JAVA, How to determine if there is more than one number that appeared...
JAVA JAVA JAVA JAVA, How to determine if there is more than one number that appeared the X amount of times. (For example there are 3 numbers which occured 50 times so I want the output to show which 3 numbers occured 50 times) This is the code import java.util.Random; public class MostLeastOccurring { public static void main(String[] args) { Random random = new Random(); int x = 1000; int[] array = new int[x]; for (int i = 0; i...
Write a java code segment to declare an array of size 10 of type String and...
Write a java code segment to declare an array of size 10 of type String and read data for them from a file, prompt user for the file name. Data is stored in a file with 1 string per line.
2. There may be only one or there may be more than one correct response to...
2. There may be only one or there may be more than one correct response to this question. You need only mark any one of the possible correct responses to be marked correct. A - Touch the top of the electroscope with your finger B - Remove your finger from the top of the electroscope C - Touch the top of the electroscope with a glass rod that was just previously rubbed by silk D - Touch the top of...
Please write code in java and comment . thanksItem classA constructor, with a String...
Please write code in java and comment . thanksItem classA constructor, with a String parameter representing the name of the item.A name() method and a toString() method, both of which are identical and which return the name of the item.BadAmountException ClassIt must be a RuntimeException. A RuntimeException is a subclass of Exception which has the special property that we wouldn't need to declare it if we need to use it.It must have a default constructor.It must have a constructor which...
(USE C ++ AND class STRING ONLY!!!! No java, No cstring and No vector) Write a...
(USE C ++ AND class STRING ONLY!!!! No java, No cstring and No vector) Write a program that can be used to train the user to use less sexist language by suggesting alternative versions of sentences given by the user. The program will ask for a sentence, read the sentence into a string variable, and replace all occurrences of masculine pronouns with genderneutral pronouns. For example, it will replace "he" with "she or he". Thus, the input sentence See an...
Write a simple Java program that does the following: 1) Declare a constant of type String...
Write a simple Java program that does the following: 1) Declare a constant of type String to hold the words "Oakland University". 2) Declare variables of the type stated, and Prompt the user to enter in the following information and store in the variables a. Their current GPA on a 4.0 scale, into a variable of type double b. The number of credits they have so far into a variable of type int c. The amount of tuition they paid...
write more than 800 words please type it Essay Topic: COMPARE AND CONTRAST THE MARKET DYNAMICS...
write more than 800 words please type it Essay Topic: COMPARE AND CONTRAST THE MARKET DYNAMICS FOR PRODUCED GOODS (AND SERVICES) WITH THE SUPPLY AND DEMAND MARKET CONDITIONS FOR LABOR. In order to help launch your mini essay, here are some things you might consider: --Identify and summarize the similar dynamics of market forces presented. That means to say, teach me step-by-step how the laws of supply and demand combine with basic assumptions about shortages and surpluses to lead to...
Please write code in java and comment . thanks Item class A constructor, with a String...
Please write code in java and comment . thanks Item class A constructor, with a String parameter representing the name of the item. A name() method and a toString() method, both of which are identical and which return the name of the item. BadAmountException Class It must be a RuntimeException. A RuntimeException is a subclass of Exception which has the special property that we wouldn't need to declare it if we need to use it. It must have a default...
Discuss why an organization may decide to target more than one market segment. If more than...
Discuss why an organization may decide to target more than one market segment. If more than one segment is targeted, what challenges do you think may exist?   
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT