[英]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.