print factorial calculation process in java

我的梦境 提交于 2019-12-02 13:33:21

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

Use this code. It checks whether you are in the last iteration and adds " * " otherwise

System.out.print(count + ((count < number) ? " * " : ""));

Otherwise you could also use:

for (count=1; count < number; count++) { // Note: < instead of <=
    factorial *= count;
    System.out.print(count + " * ");
}
factorial *= number;
System.out.println(number + " = " + factorial);

Something like this should accomplish what you're looking for:

        int number = 5;
        int factorial = 1;
        String factString = "";
        for (int count = number; count > 0; count--) {
            factorial = factorial * count;
            if (count == number) {
                factString += count;
            } else {
                factString += " * " + count;
            }
        }

        System.out.println("Factorial of " + factString + " is " + factorial);
        System.out.println();

The code will count down from the number entered. This will print all in one line by storing your progress in a string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!