设置新部分时,我需要跟踪计数器。
例如,如果m1是Brass,而我使用setSection(Strings);
我想要黄铜和弦乐++
但我不确定如果有陈述该怎么做
而且我不确定getSection()toString()是否会让我得到原始部分

/**This function sets a musician's Orchestra Section.
 @param section  is a SymphonySection indicating the musician's Orchestra Section.*/

 public void setSection(SymphonySection section) {
    this.section = section;

    if (getSection().toString().equals( "Strings" )){
        Strings--;
    }
    else if (getSection().toString().equals( "Brass" )){
        Brass--;
    }
    else if (getSection().toString().equals( "Conductor" )){
        Conductor--;
    }
    else if (getSection().toString().equals( "Percussion" )){
        Percussion--;
    }
    else if (getSection().toString().equals( "WoodWinds" )){
        WoodWinds--;
    }

    if (section.toString().equals( "Strings" )){
        Strings++;
    }
    else if (section.toString().equals( "Brass" )){
        Brass ++;
    }
    else if (section.toString().equals( "Conductor" )){
        Conductor ++;
    }
    else if (section.toString().equals( "Percussion" )){
        Percussion ++;
    }
    else if (section.toString().equals( "WoodWinds" )){
        WoodWinds ++;
    }

}

最佳答案

您的SymphonySection类是否具有toString方法,该方法在其中返回节名称?如果不是,则需要实现它,以便它返回节名,例如黄铜,琴弦等。在此处how进行检查以在SymphonySection类中实现
我建议使用switch(从Java 7开始支持Strings)语句来将内容整理整齐,或者使用Peter Lawrey建议的地图
还请查看Java命名约定here,以使您的代码更具可读性。在上述情况下,我猜StringsBrass等是类型SymphonySection的变量,因此应该使用小写的首字符,例如stringsbrassWoodWinds将是woodWinds,它遵循常规的驼峰式编码风格。


希望这可以帮助。

海登

09-10 08:46
查看更多