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.