我需要编写一款Java程序,可以告诉您字符串中的括号是否平衡。虽然我已经知道要使用循环来计算开放和关闭的括号
我只是不知道如何以这种方式计算括号。
编辑:为了更清晰,我真正需要的只是一种计算括号的方法,而我被阻塞了,因为我无法使用类似于以下代码的内容:
"(" = 1 and ")" = -1
,并将其存储在一个整数中,该整数将返回为0
或其他值,但是我无法找到正确的方法来做到这一点。我只是不知道如何以这种方式计算括号。
编辑:为了更清晰,我真正需要的只是一种计算括号的方法,而我被阻塞了,因为我无法使用类似于以下代码的内容:
if (args[i] == '(') //解释器不允许我将字符串与字符进行比较 count++;
编辑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!");
}
}
这就是我要的代码(我试图让toCharArray()方法工作,但是我一直在第三行得到“class expected”错误。那行代码存在的原因是它不允许我这样做:args.toCharArray)
请记住,我需要用输入来完成此操作,而不是使用已经存在于代码中的字符串。
))((
是错误的,而()()
则是正确的,在这两种情况下,都将返回0
。 - Fran Montero