Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Balanced parenthesis, how to count them?

Tags:

java

string

I need to write a java program that tells you if the parenthesis are balanced in a string, I can't find the correct way to do it though. I already know I am going to use a loop to count the open and closed parenthesis "(" = 1 and ")" = -1 stored in an integer that would come back as 0 or anything else.

I just don't know how to count the parenthesis that way.

Edit: To be clearer, all i really need is a way to count the parentheses and i am blocked because i can't work with something like :

if (args[i] == '(') //the interpreter will not let me compare strings with chars count++;

Edit 2 :

public class Testing_grounds {
    public static void main(String[] args) {
        String str = args[];
        char RetV[] = str.toCharArray();
        int counter = 0;
        for (int n = 0; n <= RetV.length; n++) {
            if (RetV[n] == '(')
                counter++;
            else if (RetV[n] == ')')
                counter--;
        }
        if (counter == 0)
            System.out.println("The parentheses are balenced!");
        else if(counter < 0)
            System.out.println("There are to many closed parenthesis!");
        else if(counter > 0)
            System.out.println("There are to many opened parenthesis!");
    }
}

This is pretty much the code i'm going for (i'm trying to get the toCharArray() method to work but i keep getting class expected error on the 3rd line. That line is there because it won't let me do : args.toCharArray)

Remember that i need to do this with an input and not a string already present in the code.

like image 567
Thierry L Avatar asked Sep 12 '25 23:09

Thierry L


1 Answers

If you scan the string character by character, then you can do something like this:

int counter = 0;
for (int i=0; i<text_length; i++) {
    if (text[i] == '(') counter++;
    else if (text[i] == ')') counter--;

    if (counter < 0) break;
}

if (counter != 0) error();

This code takes into account the order of the parenthesis, so ")(" will be detected as an error.

EDIT:

To do the same in Java you can do:

int counter = 0;
for (char ch : text.toCharArray())
    if (ch == '(') counter++;
    else if (ch == ')') counter--;

    if (counter < 0) break;
}
if (counter != 0) error();

Hope it helps.

like image 137
castarco Avatar answered Sep 15 '25 12:09

castarco