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));
}
}
You are almost there. You are missing some code in your main
:
System.out.println
for that.int
the user enters. You can use Scanner.nextInt
for that.for
loop with variable i
that goes from 0
to the number entered by the user.System.out.println(i + "! = " + factorial(i))
in the body of the loop.Once you finish the four steps above, you are done!