I am supposed to be creating a recursive function within Java that prints out all possible colors from a list of colors. E.G.{r, b, g ; r, g, b ; g, r, b ; g, b, r} etc…
I believe I had it figured out and my code is below. Unfortunatly I continue to recieve a null pointer exception within the base case of the recursion function and it never runs. I’ve included a test within my application test class to show that the list of colors is in fact created. I am unsure as to what is causing my error, or where I have erred in my code.
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);
}
}
Your class has a private data member named prefix, which you don’t initialize in the constructor:
Then you have a method that declares a local variable List named prefix:
Do you mean to use the private data member here?
Why do you pass in colors? How is that related to the private data member?
I don’t understand this code after a quick glance. Do you?