Question

In: Computer Science

Java Programming Using the class below, please ), write a static method called parse that parses...

Java Programming

Using the class below, please

  1. ), write a static method called parse that parses a String for balanced parentheses. we seek only to determine that the symbol ‘{‘ is balanced with ‘}’. parse accepts a single String parameter and returns an int. If parse returns a minus 1, then there are no errors, otherwise, parse should return the position within the String where an error occurred. For example

parse(“{3 + {4/2} }”)   would return -1

parse(“{ { 4*X}”) would return 6 since at position 6 we expected another “}”

parse(“{3+4}}”) would also return a 6

Solutions

Expert Solution

WORKING OF THE CODE IS EXPLAINED IN SUMMARY

CODE:

import java.util.*;
public class BalancedString
{
public static int parse(String s)
{
Deque<Character> stack = new ArrayDeque<Character>();
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(c=='{' || c=='(' || c=='[') //Push all the opening parantheses in the stack
{
stack.push(c);
}
else if((c==')' || c=='}' || c==']') && stack.isEmpty()) //Check if an extra closing parantheses encountered
{
return i+1;
}
else if(c==')') //Check if the ending parantheses was started by its balanced opening parantheses
{
char x=stack.pop();
if(x!='(')
return i+1;
}
else if(c=='}') //Check if the ending parantheses was started by its balanced opening parantheses
{
char x=stack.pop();
if(x!='{')
return i+1;
}
else if(c==']') //Check if the ending parantheses was started by its balanced opening parantheses
{
char x=stack.pop();
if(x!='[')
return i+1;
}
}
if(stack.isEmpty()) //If stack is empty than the string was correct
return -1;
else //If the stack contains any brackets than the string is incorrect
return s.length(); //The closing bracket was required at last position
}
   public static void main(String[] args) {
       int balance;
       balance=parse("{3+{4/2}}");
       if(balance==-1)
       System.out.println("No Errors found in the string");
       else
       System.out.println("Error occurred at position: "+balance);
       balance=parse("{{4*X}");
       if(balance==-1)
       System.out.println("No Errors found in the string");
       else
       System.out.println("Error occurred at position: "+balance);
       balance=parse("{3+4}}");
       if(balance==-1)
       System.out.println("No Errors found in the string");
       else
       System.out.println("Error occurred at position: "+balance);
   }
}

OUTPUT:

No Errors found in the string                                                                                                 

Error occurred at position: 6                                                                                                 

Error occurred at position: 6

Note: If you have any queries than let me know in the comments. If you find it helpful than a Like would be appreciated.

SUMMARY:

The above code is implemented as instructed. The working of code is explained in comments of the code. We push all the strating brackets like (,{,[ in the stack and search for their closing brackets in the string. If the closing bracket is found than the element from the stack is popped. If the stack is empty and the closing bracket appears than the error occurs at that index. If the string has been traversed and yet the stack is not empty that means closing bracket is not encountered for any of the starting bracket which returns that index. If the closing bracket is not matched with the top element in stack to be popped, it means there is missing closing bracket for it and therefore return that index. For example if '(' is encountered and pushed, than ')' should be encountered. But if any other closing bracket like '}' or ']' is found than it is error and hence return that index.


Related Solutions

in Java language, in most simple algorithm Using a stack class, write a static method called...
in Java language, in most simple algorithm Using a stack class, write a static method called parse that parses a String for balanced parentheses. we seek only to determine that the symbol ‘{‘ is balanced with ‘}’. parse accepts a single String parameter and returns an int. If parse returns a minus 1, then there are no errors, otherwise, parse should return the position within the String where an error occurred. For example parse(“{3 + {4/2} }”)   would return -1...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a counter and then increments the number of seconds. The counter will start at 00:00 and each time the number of seconds reaches 60, minutes will be incremented. You will not need to implement hours or a sleep function, but if minutes or seconds is less than 10, make sure a leading zero is put to the left of the number. For example, 60 seconds:...
USING JAVA: complete the method below in the BasicBioinformatics class. /** * Class BasicBioinformatics contains static...
USING JAVA: complete the method below in the BasicBioinformatics class. /** * Class BasicBioinformatics contains static methods for performing common DNA-based operations in * bioinformatics. * * */ public class BasicBioinformatics { /** * Calculates and returns the number of times each type of nucleotide occurs in a DNA sequence. * * @param dna a char array representing a DNA sequence of arbitrary length, containing only the * characters A, C, G and T * * @return an int array...
Java program Write a class called Animal that contains a static variable called count to keep...
Java program Write a class called Animal that contains a static variable called count to keep track of the number of animals created. Your class needs a getter and setter to manage this resource. Create another variable called myCount that is assigned to each animal for each animal to keep track of its own given number. Write a getter and setter to manage the static variable count so that it can be accessed as a class resource
USING JAVA: complete these one method in the BasicBioinformatics class /** * Class BasicBioinformatics contains static...
USING JAVA: complete these one method in the BasicBioinformatics class /** * Class BasicBioinformatics contains static methods for performing common DNA-based operations in * bioinformatics. * * */ public class BasicBioinformatics { /** * Calculates and returns the reverse complement of a DNA sequence. In DNA sequences, 'A' and 'T' * are complements of each other, as are 'C' and 'G'. The reverse complement is formed by * reversing the symbols of a sequence, then taking the complement of each...
Using maps in Java. Make a public class called ExampleOne that provides a single class (static)...
Using maps in Java. Make a public class called ExampleOne that provides a single class (static) method named firstOne. firstOne accepts a String array and returns a map from Strings to Integer. The map must count the number of passed Strings based on the FIRST letter. For example, with the String array {“banana”, “apples”, “blueberry”, “orange”}, the map should return {“b”:2, “a”:1, “o”:1}. Disregard empty Strings and zero counts. Retrieve first character of String as a char using charAt, or,...
Write a class in Java called 'RandDate' containing a method called 'getRandomDate()' that can be called...
Write a class in Java called 'RandDate' containing a method called 'getRandomDate()' that can be called without instantiating the class and returns a random Date between Jan 1, 2000 and Dec 31, 2010.
JAVA: USE SWITCH METHOD Write a Temperature class using the Demo below. The class will have...
JAVA: USE SWITCH METHOD Write a Temperature class using the Demo below. The class will have three conversion methods: toCelcius(), toKelvin and toFahrenheit(). These methods will return a Temperature in those three scales equal to this temperature. Note that the value of this is not changed int these coversions. In addition to these conversion methods the class will have add(Temperature), subtract(Temperature), multiply(Temperature) and divide(Temperature). These four methods all return a temperature equalled to the respective operation. Note that the this...
Write a class called VLPUtility with the following static methods: Java Language 1. concatStrings that will...
Write a class called VLPUtility with the following static methods: Java Language 1. concatStrings that will accept a variable length parameter list of Strings and concatenate them into one string with a space in between and return it. 2. Overload this method with two parameters, one is a boolean named upper and one is a variable length parameter list of Strings. If upper is true, return a combined string with spaces in upper case; otherwise, return the combined string as...
****in java please*** Create a class CheckingAccount with a static variable of type double called interestRate,...
****in java please*** Create a class CheckingAccount with a static variable of type double called interestRate, two instance variables of type String called firstName and LastName, an instance variable of type int called ID, and an instance variable of type double called balance. The class should have an appropriate constructor to set all instance variables and get and set methods for both the static and the instance variables. The set methods should verify that no invalid data is set. Also...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT