0
我應該在Java中創建一個遞歸函數,打印出顏色列表中所有可能的顏色。 E.G. {r,b,g; r,g,b; g,r,b; g,b,r}等...使用Java創建遞歸函數,打印列表中所有可能的項目序列。
我相信我已經想通了,我的代碼在下面。不幸的是,我繼續在遞歸函數的基本情況下收到一個空指針異常,它從不運行。我在應用程序測試類中包含了一個測試,以顯示顏色列表實際上已創建。我不確定是什麼導致了我的錯誤,或者我在代碼中犯了什麼錯誤。
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SequentialPrint {
private List colors;
private List prefix;
public SequentialPrint(List colors) {
this.colors = colors;
}
public void printAllSequences(List colors) {
int prefixCount = 0;
int colorCount = 0;
List prefix = new ArrayList();
if (colors.isEmpty() || prefixCount == colors.size()) { //Base Case
System.out.print("All Sequences Printed");
}
else {
Object color = colors.remove(0);
prefix.add(color); //add first color from colors list.
prefixCount++; //increases prefix counter
while (prefixCount <= colors.size() + 1) { //prints first rotation of colors
System.out.println(prefix);
System.out.print(colors);
while (colorCount < colors.size() - 1) { //rotates list and prints colors, until entire list has been rotated once.
Collections.rotate(colors, 1);
System.out.println(prefix);
System.out.print(colors);
}
}
}
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Cash
*
*/
public class SequentialPrintDemonstration {
private SequentialPrint colorSequence;
private List colorsList;
private List prefixList;
/**
* @param args
*/
public SequentialPrintDemonstration() {
List colorsList = new ArrayList();
colorsList.add("blue");
colorsList.add("green");
colorsList.add("red");
colorsList.add("yellow");
colorSequence = new SequentialPrint(colorsList);
System.out.println(colorsList);
}
public void execute() {
this.colorSequence.printAllSequences(colorsList);
}
}
發佈堆棧跟蹤;它會告訴你到底在哪個文件中出現了NPE。然後在IDE中打開該文件,轉到該行並查找解除引用的對象。其中一個是空的 - 你需要找出你未能正確初始化的地方。 NPE是最容易發現的錯誤之一。 – duffymo
你的代碼似乎根本沒有使用遞歸。它使用迭代。 –
它看起來像你在想整個事情。如果你是班級中的學生,我認爲你是... ...那麼這裏是我對你的建議......閱讀教授發佈的這篇作業的幫助筆記。它在psuedocode中附帶解決方案代碼! – 2011-10-02 05:23:50