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.
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...
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...
(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...
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...
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...
Write in Java: Write a method called: public static String[] noIdenticalCombine(String[] array1, String[] array2) { //...
Write in Java: Write a method called: public static String[] noIdenticalCombine(String[] array1, String[] array2) { // instructions: returns an array that contains all the Strings in array1 and array2 but without repetition. order does not matter, but it will return array1's elements and then array2's element that are not in array1. Assume there are no duplicates are in array1 and array2. Could use count which is how many str there are in array2, where !contains(array1, str). May an array of...
In JAVA please! The log class will allow to store multiple string messages but one at...
In JAVA please! The log class will allow to store multiple string messages but one at a time (via record(..)), and also get back the whole sequence of messages (via read()). assume and gurantee that each message is a single line of text. the fields can be of my/your choice four different methods in this class include; public Logger() . establishes a new and empty log. public Log duplicate() . this is not a constructor, but creates a no-aliases copy...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT