Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. ## 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
`5! = 120`
, as it should. Here's the code:

```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:

```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;

}
}```

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

2. ## Re: Factorial program

it outputs 0
What is the value of total when
total *= i;
is executed?

3. ## The Following User Says Thank You to Norm For This Useful Post:

rchirino (March 2nd, 2014)

4. ## Re: Factorial program

Oh... Fixed. Thanks Norm. Gotta pay more attention.