NetBeans编写Java儿歌代码时指定歌词行重复输出问题如何解决
问题根因
你定义的ifYoureHappyVerse方法内部包含了then your face will surely show it这行歌词的输出逻辑,而你在main方法中连续调用了3次该方法,所以这行内容自然会被重复输出3次。
可行修改方案
方案1:拆分输出逻辑(推荐)
把仅需要输出1次的歌词抽到方法外部,单独调用输出,拆分后的代码如下:
public static void main(String[] args) { // 三次输出带动作的歌词行 printActionLine("clap your hands", "(clap clap)"); printActionLine("clap your hands", "(clap clap)"); printActionLine("clap your hands", "(clap clap)"); // 单独输出仅需展示一次的结尾歌词 System.out.println("If you're happy and you know it, then your face will surely show it"); } // 封装动作行的输出逻辑 public static void printActionLine(String action, String sound) { System.out.println("If you're happy and you know it, " + action + sound); }
方案2:新增参数控制输出逻辑
如果不想拆分原有方法,可以新增布尔参数控制是否输出结尾歌词:
public static void main(String[] args) { ifYoureHappyVerse("clap your hands", "(clap clap)", false); ifYoureHappyVerse("clap your hands", "(clap clap)", false); // 最后一次调用时再输出结尾行 ifYoureHappyVerse("clap your hands", "(clap clap)", true); } public static void ifYoureHappyVerse(String action, String sound, boolean showEndLine) { System.out.println("If you're happy and you know it, " + action + sound); if (showEndLine) { System.out.println("If you're happy and you know it, then your face will surely show it"); } }
注:原代码中System.out.println语句末尾缺少分号,修改时记得补上避免编译报错。
内容的提问来源于stack exchange,提问作者Pain
相关产品推荐
相关产品推荐

