我应该在Java中创建一个递归函数,从一系列颜色中打印出所有可能的颜色。 E.G. {r,b,g; r,g,b; g,r,b; g,b,r}等...
我相信我弄清楚了,我的代码在下面。不幸的是,我继续在递归函数的基本情况下收到空指针异常,它永远不会运行。我在我的应用程序测试类中包含了一个测试,以显示实际创建的颜色列表。我不确定导致我的错误的原因,或者我的代码中出错的地方。
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);
}
}
答案 0 :(得分:1)
您的类有一个名为prefix的私有数据成员,您不在构造函数中初始化:
public class SequentialPrint {
private List colors;
private List prefix;
public SequentialPrint(List colors){
this.colors = colors; // what if the array you pass in is null?
// why not initialize prefix here? it's null if you don't.
}
然后你有一个方法声明一个名为prefix的本地变量List:
public void printAllSequences(List colors){
int prefixCount = 0;
int colorCount = 0;
List prefix = new ArrayList(); // this one shadows the private data member
您的意思是在这里使用私人数据成员吗?
为什么要传递颜色?这与私有数据成员有什么关系?
快速浏览后,我不明白这段代码。你呢?