Question

Can anyone help with my java factorial assignment? i think im doing it right but im not for sure. I need to have the user input a number and then calculate the factorials of the input number. Like is the person enter 10, the user would see this as an output: 0! = 1, 1! = 1, 2! = 2, 3! = 6, 4! = 24, 5! = 120, 6! = 720, 7! = 5040, 8! = 40320, 9! = 362880

import java.lang.Math;
import java.util.Scanner;

public class Factorial {

public static int factorial( int iNo ) {
    if (iNo < 0) throw
        new IllegalArgumentException("iNo must be >= 0");

    int factorial = 1;
    for(int i = 2 ; i <= iNo; i++)
        factorial *= i;
    System.out.println ( i + "! = " + factorial(i));

    return factorial ;
}
}
public class Factorial{
    public static void main ( String args[] ){
        Scanner input = new Scanner (System.in);
        System.out.println("Enter number of factorials to calculate: " );
        int  iNo = input.nextInt();
        for(int i = 0; i <= iNo; i++)
        factorial *= i;
        System.out.println ( i + "! = " + factorial(i));


}
}
Was it helpful?

Solution

You are almost there. You are missing some code in your main:

  1. Prompt the user to enter a number. You can use System.out.println for that.
  2. Read an int the user enters. You can use Scanner.nextInt for that.
  3. Set up a for loop with variable i that goes from 0 to the number entered by the user.
  4. Call System.out.println(i + "! = " + factorial(i)) in the body of the loop.

Once you finish the four steps above, you are done!

OTHER TIPS

It's good, but you don't need the }.

import java.lang.Math;

    public class Factorial {



    public static int factorial( int iNo ) {

        // Make sure that the input argument is positive

        if (iNo < 0) throw
            new IllegalArgumentException("iNo must be >= 0");

        // Use simple look to compute factorial....

        int factorial = 1;
        for(int i = 2; i <= iNo; i++)
            factorial *= i;

        return factorial;
    }


    public static void main ( String args[] ) {




    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top