A
A
Artem2021-09-05 17:49:57
Java
Artem, 2021-09-05 17:49:57

Why StackOverFlowError?

class Factorial {
  int factor(int n) {
    if (n != 1)
      return factor(n-1) * n;
    else
      return 1;
  }
}

class Main {
  public static void main(String[] args) {
    Factorial f = new Factorial();
    
    for (int i = 0; i < 1; i++) {
      System.out.println(f.factor(i));
    }
  }
}


The code is executed on the android application Jvdroid.

If you remove the loop and replace the argument with 10, then everything works

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2021-09-05
@Trame2771

Debugging in the teeth and debugging.
You pass 0 to the factor. The if works. It then calls factor with -1. And so on until stack overflow.
The factorial of zero usually has its own treatment ;-)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question