你好我正在玩StringBuffer和StringBuilder,這是我寫的一個小程序,以幫助我瞭解它是如何工作的。然而奇怪的東西與Stringbuffer沒有關係,但是我的多for if語句在我的for循環中。多如果其他如果陳述
我的小碼:
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語句在pre之後執行EVEN如果或者如果陳述已經被執行,則是虛僞的。
+1。我也建議使用'switch-case'來達到這個目的。 – BackSlash
這次你比較快。 :) – Zong
哈哈謝謝,它總是我看不到的簡單的東西 – JFC