MetalMuzu MetalMuzu - 3 months ago 6
Java Question

print factorial calculation process in java

Hi I need to print process of factorial calculation.
E.g. If the user's input is 5, the system should print out "5 * 4 * 3 * 2 * 1 = 120"

I have this code:

public static void factorial()
{
Scanner sc = new Scanner(System.in);
int factorial = 1;
int count;

System.out.println(me+", This is option 2: Calculate a factorial");
System.out.print("Enter your number: ");
int number = sc.nextInt();
System.out.println();

if (number>0)
{
for (count=1; count<=number; count++)

factorial = factorial*count;

System.out.println(" = "+factorial);
System.out.println();
}
else
{
System.out.println("Enter a positive whole number greater than 0");
System.out.println();
}

}


I have tried insert this code:

System.out.print(count+" * ");


But the output is "1 * 2 * 3 * 4 * 5 * = 6". So the result is wrong too.
How can I change the code?
Thanks

Answer

The problem is that you didn't put braces {} on your for statement:

if (number>0)
{
    for (count=1; count<=number; count++)
    {
        factorial = factorial*count;
        System.out.print(count);
        if(count < number)
            System.out.print(" * ");
    }

    System.out.println("Factorial of your number is "+factorial);
    System.out.println();
}

Also, if you're concerned about the order (1,2,4,5 instead of 5,4,3,2,1) you could do the following (changing the for loop):

if (number>0)
{
    for (count=number; count>1; count--)
    {
        factorial = factorial*count;
        System.out.print(count);
        if(count > 2)
            System.out.print(" * ");
    }

    System.out.println("Factorial of your number is "+factorial);
    System.out.println();
}