Artifacialic - 4 months ago 37

Java Question

so I'm back with a new question which is the following:

I need to calculate the factorial of a user-input, now my problem is that I can't find any code nor explanation on how to do something like this, I also saw a topic on Stackoverflow but it didn't help me any further and I don't know where to start the only thing I have is the following:

`public static void main(String[] args) throws IOException {`

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String invoer;

System.out.print("Fill in a Number:");

invoer = br.readLine();

}

so that's not much, I hope u guys can help me out!

Kind Regards,

Mikey

Answer

Code which is use to calculate factorial given input number from the user:

```
import java.util.Scanner;
class Factorial
{
public static void main(String args[])
{
int n, c, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
```

OR
**In more modular way**

```
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println("The factorial of " + n + " is " + result);
}
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
}
```