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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With