문제

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");
}
도움이 되었습니까?

해결책

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");
}

다른 팁

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");
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top