Using the NetBeans IDE, create a new project
Name the class as FactorialCalculator
Write a simple factorial calculator program. The program should perform the following
step 1. Ask the user to enter a positive integer
step 2. Check if the entered integer is positive or negative. if it is positive, perform step 3; otherwise, display an appropriate error message and the program should stop.
step 3. Calculate the factorial of the entered positive integer and display the result.
Note: The factorial of n is denoted by n! and calculated by the product of integer numbers from 1 to n. For example, the entered integer is 5, the calculation of its factorial is: 5! = 1 x 2 x 3 x 4 x 5 = 120.
Step 4. Repeat Step 1 to Step 3 five(5) times
import java.util.*;
public class FactorialCalculator {
/**
* The start point of the program
*
* @param args
*
*/
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
// step 1. Ask the user to enter a positive integer
System.out.print("Enter a positive integer: ");
int positiveInteger = keyBoard.nextInt();
// step 2. Check if the entered integer is positive or negative. if it is
// positive, perform step 3;
// otherwise, display an appropriate error message and the program should stop.
if (positiveInteger > 0) {
// step 3. Calculate the factorial of the entered positive integer and display
// the result.
// Note: The factorial of n is denoted by n! and calculated by the product of
// integer numbers from 1 to n.
// For example, the entered integer is 5, the calculation of its factorial is:
// 5! = 1 x 2 x 3 x 4 x 5 = 120.
int fact = 1;
for (int j = 1; j <= positiveInteger; j++) {
fact = fact * j;
}
System.out.println("The factorial of "+positiveInteger+": "+fact);
}else {
System.out.println("The input value is not positive.");
break;
}
}// Step 4. Repeat Step 1 to Step 3 five(5) times
keyBoard.close();
}
}
Comments
Leave a comment