[英]Method is being called 8 times and I do not understand why?
My test review is asking "How many times will niceHippo () be called?" 我的测试评论询问“将多次调用niceHippo()?” 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
正确的答案是8。无论我怎么看,我都很难理解,我看不到它在8中的效果如何。请帮助
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);
}
}
在您的代码中,您要for (int order = 1; order < 5; ++ order)
从order = 1到4迭代外循环for (int order = 1; order < 5; ++ order)
并且对于每次迭代,将for (int copy = 1; copy <= 2; copy++)
复制值for (int copy = 1; copy <= 2; copy++)
迭代是1和2以及niceHippo
从内环调用,所以作为结果niceHippo
正在被呼叫的8倍
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
对于使用copy的循环,每次运行时,您都会打印两次漂亮的河马,因为
copy <=2
然后使用order的循环将要求该copy循环运行4次,因为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. 因此最后,漂亮的河马打印了8次,因为一个循环将漂亮的河马打印了两次,并要求外部循环将其打印4次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.