Search code examples
javafactorial

Java Factorial Calculation for program can not do 0,1,2 How can I fix this


// Factorial Calculation
                double factorial = 1;
                factorial = firstNumber;
                for(double i = factorial-1; i > 1; i--){
                       factorial = factorial * i;
                       // Makes result equal to the firstNumber
                       result = factorial;
                     // To continue the program
                     continue;

                 }
                // Displays the result for factorial
                System.out.println("factorial of " + firstNumber + " is " + form.format(result));
                // To continue the program
                    continue;

So I have to a calculator by using switch statements everything works except for when I do the factorial calculation, if I enter 0,1 or 2 the answer is always 0, but from 3 to 10 the answer is always correct. So firstNumber is the variable that the user inputs. Factorial is the number it will calculate I had to make it like this so when I display my message the firstNumber equals the number not the result.


Solution

  • Your result is presumably initialized to 0 (e.g. int result = 0;).

    What is happening is that when you enter a number smaller than 3, that means factorial-1 is smaller than 2, and since we're dealing with integers, that means not larger than 1. The condition of your loop is that i must be larger than 1, so you never enter your loop, and result never changes from its initial value. A quick fix could be to simply change i > 1 to i > 0; there is no harm in multiplying by 1 anyway.

    You should also initialize result to 1, since you won't enter your loop for the values 0 and 1, but that's fine since their factorials are both 1.