我正在测试一个算术公式(例如 ((5-6)/(3+2)*34) )是否具有平衡括号,但是我检查左右括号的循环没有返回相等。我只是在提示时在控制台中输入“()”来测试它。
for (int i = 0; i < formula.size(); i++)
{
char c = formula.pop();
if (c == ')') {
right++;
break;
} else if (c == '(') {
left++;
break;
} else {
break;
}
}// End for loop
//System.out.println("There are " + left + " left parens, and " + right + " right parens.");
if (right == left)
System.out.println("The parentheses are balanced.");
else
System.out.println("The parentheses are NOT balanced.");
我的左右变量初始化为0,我得到的输出是有1个右括号和0个左括号。
有什么想法吗?我写的时候听起来/看起来是对的。
更新:这是我的代码更新为使用 switch case 而不是 if else。虽然仍然得到相同的输出..
for (int i = 0; i < formula.size(); i++)
{
char c = formula.pop();
switch(c)
{
case ')':
right++;
break; //Which breaks the switch, not the for
case '(':
left++;
break; //We don't need to do anything if it's neither.
}// End switch
}// End for loop
更新#2:这是我最近更改的所有主要内容:
public static void main(String[ ] args) {
//variables
String formulaString;
Stack<Character> formula = new Stack<Character>();
int right = 0;
int left = 0;
Scanner in = new Scanner(System.in);
System.out.println("Welcome, enter a mathmatical formula and I will "
+ "determine if the parentheses are balanced.\n");
formulaString = in.next();
for (int j = 0; j < formulaString.length(); j++) {
formula.push(formulaString.charAt(j));
}// End for loop
System.out.println("Preview of the formula just entered: ");
System.out.println(formula.display());
System.out.println("The size of the stack is: " + formula.size());
System.out.println("/******************************************");
for (int i = 0; i <= formula.size(); i++)
{
char c = formula.pop();
System.out.println(c);
switch(c)
{
case ')':
right++;
break; //Which breaks the switch, not the for
case '(':
left++;
break; //We don't need to do anything if it's neither.
}// End switch
}// End for loop
System.out.println("There are " + left + " left parens, and " + right + " right parens.");
if (right == left)
System.out.println("The parentheses are balanced.");
else
System.out.println("The parentheses are NOT balanced.");
}// End main.
我现在正在测试的输入是(())
. 我得到它的输出:
Preview of the formula just entered:
[(, (, ), )]
The size of the stack is: 4
/******************************************
)
)
(
There are 1 left parens, and 2 right parens.
The parentheses are NOT balanced.