如果其他如果是法定的

JFC*_*JFC 0 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);
        }
    }

}
}
Run Code Online (Sandbox Code Playgroud)

预期的输出将是这样的:

Your current infix expression: 3/8)
Digit 3 at: 0
Operator at: 1
Digit 8 at: 2
) found at: 3
Run Code Online (Sandbox Code Playgroud)

然而,世界并不是完美的圆形所以我的输出出来了:

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
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,由于某种原因,在我的for循环中,最后一个if语句正在执行EVEN之前的if或else if语句已被执行.

rge*_*man 7

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

else if(infixB.charAt(i) == ')');
Run Code Online (Sandbox Code Playgroud)

else if(infixB.charAt(i) == ')')
Run Code Online (Sandbox Code Playgroud)