In: Computer Science
In Java
In mathematics, factorial of a non-negative integer n, denoted by n! , is the product of all positive integers less than or equal to n. For example,
5! = 5 * 4 * 3 * 2* 1 = 120
3! = 3 * 2 * 1 = 6
2! = 2 * 1 = 2
The value of 0! is 1.
Write a program that asks user to enter an integer > 0; if a valid value is entered, it should calculate and display factorial of the number entered. If the user enters an integer <=0, display a message "Invalid entry - valid entry is an integer > 0" and have them re-enter the information.
please check screenshots for better understanding. Any doubts comment below.Thank you.
JAVA CODE:
import java.util.*;
public class Factorial {
public static void main(String args[])
{
System.out.print("Enter an integer
>0:"); //Display user to enter an integer >0
Factorial.fact(); // calling method
fact
}
public static void fact() // creating method
fact
{
Scanner sc = new
Scanner(System.in);
int n=sc.nextInt(); // Taking input
from user
if(n<=0)
{
System.out.println("Invalid entry - valid entry is an integer >
0");
System.out.print("re-enter valid value:"); //if the input value is
asking user to re-enter value
Factorial.fact();
}
else
{
int f = 1;
for(int
i=1;i<=n;i++) //loop for calculating factorial of an
integer
{
f = f*i;
}
System.out.println("The value of "+n+"! is "+f); // printing
factorial of an integer
}
}
}