Eloienai John S.
Soriano
BTVT Ed - 2C
CPC07 Object Oriented Programming
import java.util.Scanner;
import java.text.NumberFormat;
public class FactorialCalculator {
// Function to calculate factorial
static long calculateFactorial(int num) {
long factorial = 1;
for (int c = 2; c <= num; c++) {
factorial *= c;
}
return factorial;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
NumberFormat formatter = NumberFormat.getInstance(); //More descriptive
variable name
String start = "(---";
String end = "---)";
System.out.println(start + "Factorial Calculator" + end);
for (int i = 0; i < 5; i++) {
System.out.print("Enter a positive integer: ");
int number;
try{
number = input.nextInt();
} catch (java.util.InputMismatchException e){
System.out.println("Invalid Input! Please enter an integer.");
input.next(); //Consume the invalid input
continue; //Skip to next iteration of the loop
}
if (number < 0) {
System.out.println("Invalid Input! Program Stopped!");
break;
}
long factorial = calculateFactorial(number);
String formattedFactorial = formatter.format(factorial);
//More readable output construction
System.out.print(number + "! = 1");
for (int j = 2; j <= number; j++) {
System.out.print(" × " + j);
}
System.out.println("\nThe factorial of " + number + " is: " +
formattedFactorial + "\n");
}
input.close(); //Good practice to close the scanner
}
}