javaloopsfactorial

Factorial Calculator


How can I make the program to perform a new or repeat the operation or ask the user to input again a number and know the factorial of it.

import java.util.Scanner;

public class Loops {

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        int num, num2 = 1, x, i;

        System.out.println("-------------Factorial Calculator-------------");
        System.out.print("Enter a positive integer: ");
        num = input.nextInt();

        if (num > 0) {
            System.out.print(num + "! = ");
            for (i = 1; i <= num; i++) {
                if(i < num){
                    System.out.print(i + " x ");
                    num2 = num2 * i;
                }
                if(i == num){
                    System.out.print(i);
                    num2 = num2 * i;
                    System.out.println("\nThe factorial of " + num + " is " + num2);
                    System.out.println();
                }
            }
        }else if (num < 0) {
            System.out.println("Please input a valid integer. Program stopped.");
        }
    }
}

Solution

  • Put the code that computes the factorial in a separate method and call it from within a loop in main().

    import java.util.Scanner;
    
    public class Loops {
    
        public static void printFactorial(int num) {
            int i = 0;
            int num2 = 0;
            if (num > 0) {
                System.out.print(num + "! = ");
                for (i = 1; i <= num; i++) {
                    if(i < num){
                        System.out.print(i + " x ");
                        num2 = num2 * i;
                    }
                    if(i == num){
                        System.out.print(i);
                        num2 = num2 * i;
                        System.out.println("\nThe factorial of " + num + " is " + num2);
                        System.out.println();
                    }
                }
            }else if (num < 0) {
                System.out.println("Please input a valid integer. Program stopped.");
                System.exit(0);
            }
    
        }
        public static void main(String[] args)
        {
            Scanner input = new Scanner(System.in);
            int num = 0;
            System.out.println("-------------Factorial Calculator-------------");
            while ( true ) {
                System.out.print("Enter a positive integer: ");
                num = input.nextInt();
                printFactorial(num);
            }
        }
    }