Search code examples
javafactorial

Why does factorial method always return the same result?


public static void main(String[] args) {

    // Luke Mihalovich

    Scanner keyboard = new Scanner(System.in);

    int n;

    System.out.print("Enter a non-negative integer (-1 to quit) : ");
    n = keyboard.nextInt();

    int factorial = Factorial(n);   

    while (n >= 1) {
        System.out.print("Enter a non-negative integer (-1 to quit) : ");
        n = keyboard.nextInt();
        System.out.println(n + "! = " + factorial);}

    if (n == 0) {
        System.out.print(n = 1); }

    if (n == -1) {
        System.out.print("Goodbye!"); }
}

public static int Factorial(int n) {

    int factorial = 1;

    for(int i= 1;i<n;) {
        i++;
        factorial = factorial * i; }

    return factorial;
    }
}

This program prints the same result for all inputs.

For example, if I input 5, the answer correctly is 5! = 120. But if I enter 4, it prints 4! = 120 again, which is wrong, it should be 24.


Solution

  • You are not calculating the factorial after taking the input in the while loop instead what you are doing is calculating the factorial once before the while loop and that printing that every time a new input is given.

    Update the main function as follows and it should work.

    public static void main(String[] args) {
    
        Scanner keyboard = new Scanner(System.in);
        int n=1;
    
        while (n >= 1) {
            System.out.print("Enter a non-negative integer (-1 to quit) : ");
            n = keyboard.nextInt();
            // Calculate the factorial for each number you take as the input
            int factorial = Factorial(n);
            System.out.println(n + "! = " + factorial);}
    
        if (n == 0) {
            System.out.print(n = 1); }
    
        if (n == -1) {
            System.out.print("Goodbye!"); }
    }