[英]Method is being called 8 times and I do not understand why?
我的测试评论询问“将多次调用niceHippo()?” 正确的答案是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倍
对于使用copy的循环,每次运行时,您都会打印两次漂亮的河马,因为copy <=2
然后使用order的循环将要求该copy循环运行4次,因为order <5
因此最后,漂亮的河马打印了8次,因为一个循环将漂亮的河马打印了两次,并要求外部循环将其打印4次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.