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 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 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 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 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
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 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 enter two characters and display the corresponding major...
Write a program that prompts the user to enter two characters and display the corresponding major and year status. The first character indicates the major. And the second character is a number character 1, 2, 3, 4, which indicates whether a student is a freshman, sophomore, junior, or senior. We consider only the following majors: B (or b): Biology C (or c): Computer Science I (or i): Information Technology and Systems M (or m): Marketing H (or h): Healthcare Management...
Write a program in JAVA that prompts the user for a lower bound and an upper...
Write a program in JAVA that prompts the user for a lower bound and an upper bound. Use a loop to output all of the even integers within the range inputted by the user on a single line.
⦁   Write a Bash script that prompts for user input and reads a string of text...
⦁   Write a Bash script that prompts for user input and reads a string of text from the user. If the user enters a no null (no empty) string, the script should prompt the user to re-enter again the string; otherwise should display the string entered “. ⦁   Given an array of the following four integers (3, 5, 13, 14); write a Bash script to display the second and all elements in the array.    ⦁   Write a short Bas...
THIS IS JAVA PROGRAMMING Guessing the Capitals. Write a program Lab5.java that repeatedly prompts the user...
THIS IS JAVA PROGRAMMING Guessing the Capitals. Write a program Lab5.java that repeatedly prompts the user to enter a capital for a state (by getting a state/capital pair via the StateCapitals class. Upon receiving the user’s input, the program reports whether the answer is correct. The program should randomly select 10 out of the 50 states. Modify your program so that it is guaranteed your program never asks the same state within one round of 10 guesses.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT