# Factorial console program

• 04-13-2010, 08:54 AM
er1c550n20
Factorial console program
hey guys i know all of can help me here. Program is about user enters a number at run time and output should give the factorial.
I feel error is really simple but couldnt sort it out.

import java.io.IOException;
public class NumberFactorial
{
public static void main(String args[])
{
int number;
try
{
System.out.println("Enter the number");

int factorial = number;
for(int i =(number-1);i>1;i--)
{
factorial=factorial*i;
}
}
catch(NumberFormatException ne)
{
System.out.println("Number Format Exception"+ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println("Input Exception Error"+ioe);
System.exit(0);
}
System.out.println("Factorial of number is:" +factorial);
}
}
• 04-13-2010, 09:00 AM
programmer_007
Code:

`System.out.println("Factorial of number is:" +factorial);`
just move this line a bit up into the try block of ur code.

please use code tags.. when u post ur code.
• 04-13-2010, 09:04 AM
JosAH
Your formula is wrong: by definition 0! == 1.

kind regards,

Jos
• 04-13-2010, 09:15 AM
programmer_007
Quote:

Your formula is wrong: by definition 0! == 1.
Code:

```try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the number"); number = Integer.parseInt(br.readLine()); int factorial=1; while(number>0) {         factorial = factorial * number;         number--; } System.out.println("Factorial of number is:" +factorial); }```
ur try block must look something like this.
• 04-13-2010, 09:46 AM
m00nchile
How about a simple recursive method?
Code:

```int factorial(int n) {   if(n == 0) return 1;   return factorial(n-1)*n; }```
• 04-13-2010, 09:55 AM
JosAH
Quote:

Originally Posted by m00nchile
How about a simple recursive method?
Code:

```int factorial(int n) {   if(n == 0) return 1;   return factorial(n-1)*n; }```

Great; factorial(-1)

kind regards,

Jos
• 04-13-2010, 02:07 PM
m00nchile
It was just a reccomendation, I know it should check for values that it can't calculate.