【发布时间】:2013-11-14 18:28:57
【问题描述】:
您好,我正在玩 StringBuffer 和 StringBuilder,这是我编写的一个小程序,用于帮助我理解它是如何工作的。然而,一些奇怪的事情出现了,与 Stringbuffer 无关,而是我的 for 循环中的 multi if else if 语句。
我的小代码:
public class c
{
public static void main(String args[])
{
StringBuffer infixB = new StringBuffer();
String infix = "3/8";
for(int i = 0; i < infix.length(); i++)
{
infixB.append(infix.charAt(i));
}
infixB.append(')');
System.out.println("Your current infix expression: "+infixB.toString());
//go through the 'infixB' 1 position at a time
for(int i = 0; i < infixB.length(); i++)
{
if(infixB.charAt(i) == '3')
{
System.out.println("Digit 3 at: " +i);
}
else if(infixB.charAt(i) == '/')
{
System.out.println("Operator at: "+i);
}
else if(infixB.charAt(i) == '8')
{
System.out.println("Digit 8 at: "+i);
}
else if(infixB.charAt(i) == ')');
{
System.out.println(") found at: " +i);
}
}
}
}
预期的输出是这样的:
Your current infix expression: 3/8)
Digit 3 at: 0
Operator at: 1
Digit 8 at: 2
) found at: 3
然而世界不是完美的圆所以我的输出出来了:
Your current infix expression: 3/8)
Digit 3 at: 0
) found at: 0
Operator at: 1
) found at: 1
Digit 8 at: 2
) found at: 2
) found at: 3
如您所见,由于某种原因,在我的 for 循环中,最后一个 else if 语句正在执行,即使在前一个 if 或 else if 语句已经执行之后。
【问题讨论】:
标签: java if-statement stringbuffer