multi if else if语句

时间:2013-11-14 18:28:57

标签: java if-statement stringbuffer

您好我正在玩StringBuffer和StringBuilder这是我写的一个小程序,以帮助我理解它是如何工作的。然而,一些奇怪的东西与Stringbuffer无关,而是我的for循环中的多if if else语句。

我的小代码:

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循环中,最后一个if语句正在执行EVEN之后的if或else if语句已被执行。

2 个答案:

答案 0 :(得分:7)

在最后一个条件结束时有一个分号。 Java会将该分号视为条件的主体,并始终将大括号中的块作为不相关的块执行。变化

else if(infixB.charAt(i) == ')');

else if(infixB.charAt(i) == ')')

答案 1 :(得分:0)

{
  System.out.println(") found at: " +i);
 }

此代码没有if条件,因此每次都显示for循环条件

相关问题