-1

My test review is asking "How many times will niceHippo () be called?" and the correct answer is 8. I'm having trouble understanding this as no matter how I look at it I'm not seeing how it results in 8. Please help

public class Animals{

    public static String niceHippo()
    {
        String hippo = "Nice Hippo";
        return hippo;
    }

    public static String niceLion(){
        String lion = "Nice Lion";
        return lion;
    }

    public static void main(String[] args){
        int count = 13;
        String stringOut = "I love this class ";
        do
        {
            stringOut = "Animals can be messy ";
            for (int order = 1; order < 5; ++ order)
                for (int copy = 1; copy <= 2; copy++)
                    System.out.println(niceHippo());
            System.out.println(niceLion());
        }while (count != 13);

        count = 13;
        while (count > 10)
        {
            count--;
        }

        System.out.println(stringOut + count);
    }
}
Jason
  • 11,744
  • 3
  • 42
  • 46
  • 4
    You might want to use a [debugger](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) for that or look at [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Andreas Feb 28 '19 at 02:20
  • 2
    *hint*: look at the nested for-loops - `4 x 2 = 8` – Kartik Feb 28 '19 at 02:21
  • How many times do you think it's being called? Why? – shmosel Feb 28 '19 at 02:23
  • @shmosel I think I might be understanding it now. Is it 8 because the nested for-loop runs twice each time and the for-loop above it runs 4 consecutive times? If so, does this mean the count variable is irrelevant for the amount of times niceHippo() is called? – Colton Behannon Feb 28 '19 at 02:30
  • Indeed it is... – shmosel Feb 28 '19 at 02:30
  • Nothing in the loop is changing the count variable from its initial value of 13. So the do loop will execute once, and the where clause will cause it to not execute again. – Jason Feb 28 '19 at 02:35

2 Answers2

0

In your code you are iterating outer loop for (int order = 1; order < 5; ++ order) for order = 1 to 4 and for each iteration copy value for (int copy = 1; copy <= 2; copy++) will be 1 and 2 and niceHippo is called from inner loop, so as a result niceHippo is being called 8 times

Jainik
  • 2,352
  • 1
  • 19
  • 27
0

For the loop using copy, each time that's ran you print nice hippo twice because copy <=2 Then the loop using order is going to ask that copy loop to run 4 times because order <5

so in the end nice hippo prints 8 times because one loop prints nice hippo twice and its asked to do that 4 times by the outer loop.