Question

In: Computer Science

Write Java code that prompts the user for a string and tells them if the grouping characters in that string are balanced.


Write Java code that prompts the user for a string and tells them if the grouping characters in that string are balanced. Grouping characters are ( and ), [ and ], and { and }. I got the basic idea for this problem from HackerRank. It’s also a very common interview question.

*******************8Example output**************

Enter the expression:{[()]} {[()]}

is balanced

Enter the expression: {()()} {()()}

is balanced

Enter the expression: {([[])} {([[])}

is not balanced

Enter the expression: {([)]} {([)]}

is not balanced

Solutions

Expert Solution

Iterate over each parantheses from start to end and do the below step at each iteration.

  1. When you find opening bracket: will go Push.
  2. When you find closing bracket: will go pop and check whether closing and opening bracket match.
  3. If yes, then continue, if not then break and return NO.

import java.util.Arrays;

import java.util.List;

import java.util.Scanner;

import java.util.Stack;

public class Parantheses {

    

    public static void main(String args[]){

        Scanner sc = new Scanner(System.in); //enter the input expression

        System.out.print("Enter the expression:");

        String inputString = sc.nextLine();

        System.out.println(checkBraces(inputString));

        sc.close();

    }

    

    static String checkBraces(String v){

        Stack charstack = new Stack(); //instance of object creation

        String r = "is not balanced"; // initialization of variables

        char tmpChar;

        Character[] openingBraces = {'[','(','{'};

        Character[] closingBraces = {']',')','}'};

        List openingBracesList = Arrays.asList(openingBraces);

        List closingBracesList = Arrays.asList(closingBraces);

       

        

        

        if(v == null){

            return r;

        }else if(v.length()==0)

{ //v is value

            r = " is balanced";

        }else{

        

            for(int i=0; i < v.length(); i++) {

                tmpChar = v.charAt(i);

                

                if(openingBracesList.contains(tmpChar)){

                    charstack.push(tmpChar);

                }else if(closingBracesList.contains(tmpChar)){

                    if(!charstack.isEmpty()){

                        if(tmpChar==')' && '(' != charstack.pop()){

                            return r;

                        }else if(tmpChar=='}' && '{' !=charstack.pop()){ //poping character

                            return r;

                        }else if(tmpChar==']' && '[' != charstack.pop()){

                            return r;

                        }

                    }else{

                        return r;

                    }

                }else{

                    return r;

                }

            }

            

        }

        

        if( charstack.isEmpty()){

            r = " is balanced";

            return r;

        }else{

            return r;

        }

    }

}

output is:


Related Solutions

Write a Java class called GuessMyNumber that prompts the user for an integer n, tells the...
Write a Java class called GuessMyNumber that prompts the user for an integer n, tells the user to think of a number between 0 and n−1, then makes guesses as to what the number is. After each guess, the program must ask the user if the number is lower, higher, or correct. You must implement the divide-and-conquer algorithm from class. In particular, you should round up when the middle of your range is in between two integers. (For example, if...
Write a Java program that prompts the user to input a string and prints whether it...
Write a Java program that prompts the user to input a string and prints whether it is a palindrome. A palindrome is a string which reads the same backward as forward, such as Madam (disregarding punctuation and the distinction between uppercase and lowercase letters). The program must use the stack data structure. The program must include the following classes: The StackX class (or you can use the Java Stack class). The Palindrome class which must contain a method named palindrome()...
Write a Java program that prompts the user to input a word (String). The program must...
Write a Java program that prompts the user to input a word (String). The program must print the reversed word with all consecutive duplicate characters removed. The program must contain the following classes: - The StackX class (you can use the Java Stack class). - The Reverse class which must contain a private data field called “word” of type string, a constructor, and a void method called revNoDup(). The revNoDup() method must reverse the word and remove the consecutive duplicate...
write this program in C++ Write a program that prompts a user for three characters. The...
write this program in C++ Write a program that prompts a user for three characters. The program must make sure that the input is a number 10 - 100 inclusive. The program must re prompt the user until a correct input is entered. Finally output the largest and the lowest value. Example 1: Input : 10 Input : 20 Input : 30 The largest is 30. The lowest is 10. Example 2: Input : 100 Input : 50 Input :...
Write a c++ code that prompts the user to enter three float numbers and print them...
Write a c++ code that prompts the user to enter three float numbers and print them in acsending order
Problem 1 Write a program that prompts the user to enter an integer It then tells...
Problem 1 Write a program that prompts the user to enter an integer It then tells the user if the integers is a multiple of 2, 3, 5, 7 or none of the above. Program language is C Ex. Enter an integer 12 You entered 12 The number you entered is a multiple of 2 ----------------------------------------------- Enter an integer 11 You entered 11 The number you entered is not a multiple of 2, 3, 5, or 7
Write a C++ Program Write a program that prompts the user to input a string. The...
Write a C++ Program Write a program that prompts the user to input a string. The program then uses the function substr to remove all the vowels from the string. For example, if str=”There”, then after removing all the vowels, str=”Thr”. After removing all the vowels, output the string. Your program must contain a function to remove all the vowels and a function to determine whether a character is a vowel. You must insert the following comments at the beginning...
Write a Python program which prompts the user to input a string. Then, print the string...
Write a Python program which prompts the user to input a string. Then, print the string in reverse to the terminal Sample output Please enter a word: "zeus" The reverse of zeus is suez Hint: There are several ways to accomplish this. Recall that a string is an itterable object and therefore can be used with a for loop
Write a MIPS assembly program that prompts the user first for a string, then for a...
Write a MIPS assembly program that prompts the user first for a string, then for a character. The program should then search the string for the character and print out the number of times the character appears in the string. You can use as many restrictions as you want, just be sure to list them. You must allocate space in the .data segment of your program for the user string.
Write a program that prompts the user to input a string. The program then uses the...
Write a program that prompts the user to input a string. The program then uses the function substr to remove all the vowels from the string. For example, if str=”There”, then after removing all the vowels, str=”Thr”. After removing all the vowels, output the string. Your program must contain a function to remove all the vowels and a function to determine whether a character is a vowel. You must insert the following comments at the beginning of your program and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT