Question

I'm trying to write a program that prints all the patterns one can make with ABC. I'm allowing the user to determine how long it characters should be, but I'm having trouble running the program because I get an error and I don't know what is wrong..

private static int userinput;

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the maximum number of characters");
    userinput = input.nextInt();
    combos();
}

public static void combos()
{
    combos("");
}

private static void combos(String counter)
{
    if (counter.length() == userinput) //base case
        System.out.println(counter);
    else //recursive case
        combos(counter + "A");
        combos(counter + "B");
        combos(counter + "C");
}
Was it helpful?

Solution

As rogue mentions, your block:

else //recursive case
    combos(counter + "A");
    combos(counter + "B");
    combos(counter + "C");

... will only execute combos(counter + "A"); contextually to the else statement.

The following recursive statements ("B" and "C") will be executed regardless of your if condition.

This is likely to cause a fault in your flow control, hence your StackOverflowError.

Add brackets to enclose your else statement:

else {//recursive case
        combos(counter + "A");
        combos(counter + "B");
        combos(counter + "C");
}

OTHER TIPS

You forgot the curly braces for the else-statement of your "recursive case" ...

This does work:

private static void combos(String counter) {
    if (counter.length() == userinput) //base case
        System.out.println(counter);
    else {
        combos(counter + "A");
        combos(counter + "B");
        combos(counter + "C");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top