According to the task it was necessary to write a function that finds the factorial of a number. If the factorial is less than zero, or more than 12, throw an IllegalArgumentException. When testing the code, something incomprehensible happens, please indicate my mistake.

public class Factorial { int factorial = 1; public int factorial(int n) { if(n < 0 || n > 12) { throw new IllegalArgumentException(); } else if(n == 0) { return 1; } for(int i = n; i < 2; i--) { factorial *= i; } return factorial; } } 
  • one
    factorial = 1; for(int i = n; i > 1; i--) { factorial *= i; } factorial = 1; for(int i = n; i > 1; i--) { factorial *= i; } - Igor
  • one
    Thanks for editing, please add an answer so that I can mark it as a solution. - Arc

2 answers 2

Probably a typo in for :

 factorial = 1; for(int i = n; i > 1; i--) { factorial *= i; } 
     for(int i = n; i < 2; i--) { factorial *= i; } 

    That is, starting with the value n , while it is less than 2, decrease ...
    Do you really want this? :)

    I would do

     for(int i = n; i >= 2; i--) { factorial *= i; } 
    • My stupidity, I completely forgot how the conditions work in this cycle =) - Arc