1. Member
Join Date
Mar 2010
Posts
9
Rep Power
0

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);
}
}

2. Java 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.

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

kind regards,

Jos

4. Your formula is wrong: by definition 0! == 1.
Java Code:
```try
{
System.out.println("Enter the number");
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.

5. Senior Member
Join Date
Feb 2010
Location
Ljubljana, Slovenia
Posts
470
Rep Power
9
How about a simple recursive method?
Java Code:
```int factorial(int n) {
if(n == 0) return 1;
return factorial(n-1)*n;
}```

6. Originally Posted by m00nchile
How about a simple recursive method?
Java Code:
```int factorial(int n) {
if(n == 0) return 1;
return factorial(n-1)*n;
}```
Great; factorial(-1)

kind regards,

Jos

7. Senior Member
Join Date
Feb 2010
Location
Ljubljana, Slovenia
Posts
470
Rep Power
9
It was just a reccomendation, I know it should check for values that it can't calculate.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•