# Factorial program

• March 2nd, 2014, 10:33 AM
rchirino
Factorial program
Hello everyone.

I'm working on some exercises and I'm having some problems with a method. I want to create a method to calculate the Factorial of an int number. I already wrote code that asks the user to input an int number and it calculates the Factorial, and it works fine (ie: if I input 5 it outputs
Code :

`5! = 120`
, as it should. Here's the code:

Code Java:

```import java.util.Scanner;   public class Factorial1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number; int total = 1;   System.out.print("Enter positive int number: "); number = input.nextInt();   while(number < 0) { System.out.print("Enter positive int number: "); number = input.nextInt(); }   for(int i = number; i > 0; i--) total *= i;   System.out.printf("%d! = %d", number, total); } }```

Now I want to make a method to re-use this code in other programs and I wrote this program:

Code Java:

```public class TestClass { public static void main(String[] args) { System.out.print(factorial(5)); }   public static int factorial(int x) { int total = 0;   for(int i = x; i > 0; i--) total *= i;   return total; } }```

But when I run this program it outputs 0 instead of 120. I don't have the slightest idea of what is wrong with this code as it compiles just fine but doesn't work as intended.

Any help will be very appreciated, and thanks in advance!

Ricardo
• March 2nd, 2014, 10:47 AM
Norm
Re: Factorial program
Quote:

it outputs 0
What is the value of total when
total *= i;
is executed?
• March 2nd, 2014, 10:51 AM
rchirino
Re: Factorial program
:eek: Oh... Fixed. Thanks Norm. Gotta pay more attention.