我是Java的新手,尝试做一些琐碎的事情和练习,但是我碰到了这个问题,当输出达到1或0时,我希望“鸭子”一词是单数,这是我的代码:

public class FiveLittleDucks {

    public static void main(String[] args) {

        String word = "";

        System.out.println("The story of the 5 little ducks");
        for(int duck = 5 ; duck>0 ; duck--) {
            if(duck == 1 || duck == 0) {
                word = "duck";
            } else {
                word = "ducks";
            }
            System.out.printf("%d little %s went out one day, over the hills and far away, mother duck said quack, quack, quack, quack", duck, word);
            System.out.printf(" but only %d little %s went back\n", duck-1, word);
        }
    }
}


这是输出:
5只小鸭子的故事

一天有5只小鸭子出山,在山上和远处,母鸭说嘎嘎,嘎嘎,嘎嘎,嘎嘎,但只有4只鸭子回去了

一天有4只小鸭子出山,在山上和远处,母鸭说嘎嘎,嘎嘎,嘎嘎,嘎嘎,但只有3只小鸭子回来了

一天有3只小鸭子出山,在远处的山丘上,鸭妈妈说嘎嘎,嘎嘎,嘎嘎,嘎嘎,但是只有两只鸭子回来了

一天有2只小鸭子出山,在山上和远处,母鸭说嘎嘎,嘎嘎,嘎嘎,嘎嘎,但只有一只鸭子回到

一天有1只小鸭子出山,在山上和远处,母鸭说嘎嘎,嘎嘎,嘎嘎,嘎嘎,但只有0只小鸭子回来了

注意“ 1只小鸭子”仍然是复数形式,而底线已经是单数形式..谢谢大家。

最佳答案

循环的每次迭代都会打印两行-一行的当前计数器为duck,另一行的为duck-1。但是,您要根据wordduck分配一个值,因此,即使duck为1,当"ducks"为2时,单词也是duck-1。解决此问题的一种方法是提取对循环中的单词并分别进行评估:

public static void main(String[] args) {
    System.out.println("The story of the 5 little ducks");
    for(int duck = 5 ; duck>0 ; duck--) {
        System.out.printf("%d little %s went out one day, over the hills and far away, mother duck said quack, quack, quack, quack", duck, ducksToWord(duck));
        System.out.printf(" but only %d little %s went back\n", duck-1, ducksToWord(duck-1));
    }
}

private static String ducksToWord(int duck) {
    if (duck == 1 || duck == 0) {
        return "duck";
    }
    return "ducks";
}

10-07 22:25