DuckStudyingJava
DuckStudyingJava

Reputation: 31

If statement inside a for loop in Java

I'm new in Java and trying to do some trivial stuffs and exercises, I came with this bump though, I want the word "ducks" to be singular when the output reaches 1 or 0, here is my code:

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);
        }
    }
}

here is the output: The story of the 5 little ducks

5 little ducks went out one day, over the hills and far away, mother duck said quack, quack, quack, quack but only 4 little ducks went back

4 little ducks went out one day, over the hills and far away, mother duck said quack, quack, quack, quack but only 3 little ducks went back

3 little ducks went out one day, over the hills and far away, mother duck said quack, quack, quack, quack but only 2 little ducks went back

2 little ducks went out one day, over the hills and far away, mother duck said quack, quack, quack, quack but only 1 little ducks went back

1 little duck went out one day, over the hills and far away, mother duck said quack, quack, quack, quack but only 0 little duck went back

notice the "1 little ducks" is still in plural form whereas the bottom line is already in singular form.. thanks guys..

Upvotes: 1

Views: 185

Answers (1)

Mureinik
Mureinik

Reputation: 311326

Each iteration of the loop prints two lines - one with the current counter of duck and one with duck-1. However, you assign a value to word based on duck, so when duck is 2 the word is "ducks", even though duck-1 is 1. One way to solve this is to extract the calculation of the word from the loop and evaluate it individually:

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";
}

Upvotes: 2

Related Questions