0

Hello I was playing around with StringBuffer and StringBuilder and this is a little program I wrote to help me understand how it work. However something strange came up not related to Stringbuffer but my multi if else if statement within my for loop.

My little code:

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);
        }
    }

}
}

the expected output would be something like:

Your current infix expression: 3/8)
Digit 3 at: 0
Operator at: 1
Digit 8 at: 2
) found at: 3

However the world is not perfectly round so my output came out:

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

As you can see, for some reason within my for loop the last else if statement was executing EVEN AFTER a previous if or else if statement has already been executed.

4

2 回答 2

7

最后一个条件的末尾有一个分号。Java 会将分号视为条件的主体,并始终将大括号中的块作为不相关的块执行。改变

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

else if(infixB.charAt(i) == ')')
于 2013-11-14T18:29:47.983 回答
0
{
  System.out.println(") found at: " +i);
 }

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

于 2013-11-18T09:19:52.370 回答