【问题标题】:multi If else if statments多 if else if 语句
【发布时间】:2013-11-14 18:28:57
【问题描述】:

您好,我正在玩 StringBuffer 和 StringBuilder,这是我编写的一个小程序,用于帮助我理解它是如何工作的。然而,一些奇怪的事情出现了,与 Stringbuffer 无关,而是我的 for 循环中的 multi if else if 语句。

我的小代码:

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

【问题讨论】:

    标签: java if-statement stringbuffer


    【解决方案1】:

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

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

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

    【讨论】:

    • +1。我还建议为此目的使用switch-case
    • 这次你速度更快了。 :)
    【解决方案2】:
    {
      System.out.println(") found at: " +i);
     }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-09
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      • 2015-07-06
      • 2012-08-05
      相关资源
      最近更新 更多