在一個初學者的編程的書(遊離執照)有下面的代碼,在Java動態創建嵌套循環:模擬嵌套循環
import java.util.Scanner;
public class RecursiveNestedLoops {
public static int numberOfLoops;
public static int numberOfIterations;
public static int[] loops;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("N = ");
numberOfLoops = input.nextInt();
System.out.print("K = ");
numberOfIterations = input.nextInt();
input.close();
loops = new int[numberOfLoops];
nestedLoops(0);
}
public static void nestedLoops(int currentLoop) {
if (currentLoop == numberOfLoops) {
printLoops();
return;
}
for (int counter=1;counter <= numberOfIterations;counter++) {
loops[currentLoop] = counter;
nestedLoops(currentLoop + 1);
}
}
public static void printLoops() {
for (int i = 0; i < numberOfLoops; i++) {
System.out.printf("%d ", loops[i]);
}
System.out.println();
}
}
我
當輸入N = 2和K = 3,屏幕上應該印有[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1], [3,2],[3,3](帶有換行符等)。該程序正常工作。 然後我試圖調試它,花了相當一段時間試圖瞭解它的工作原理。我不能。我的問題:
---->爲什麼打印後[1,3]變量'curentLoop'變成'0'事先是'1'?在我的調試器(Eclipse內置)中打印後[1,3],指針會進入方法'nestedLoops'的最後'}'括號('currentLoop'值爲1) ,然後突然開始執行「currentLoop」= 0的for循環。變量從哪裏取值爲0?爲什麼在進入方法的最後一個大括號之後,它會開始執行'for循環',而無需調用方法的名稱?
這對於你們中的一些人來說可能是一個非常簡單的問題;我只是一個初學者。預先感謝您的幫助。
作爲一個方面說明,這是非常可怕的代碼。在製作世界中你永遠不會看到這樣的事情。這很可怕。 – 2009-08-21 19:01:38
不過,我認爲看它是如何工作的很有教育意義。 – Imagist 2009-08-21 19:21:40
@imagist是的,我會去那。當他們開始接觸這些東西時,很容易彎曲頭腦。更多的是一些開發者從來沒有學會去避免這種類型的編程,如果它編譯並運行,那很好!「的態度,從不考慮代碼隨着時間的推移調試和維護的複雜程度。 – 2009-08-21 19:26:59