[go: up one dir, main page]

0% found this document useful (0 votes)
11 views1 page

CPC07 Object Oriented Programming

The document contains a Java program for calculating the factorial of a positive integer using object-oriented programming principles. It includes error handling for invalid inputs and formats the output for better readability. The program allows the user to input up to five integers and displays the factorial for each valid input.

Uploaded by

Ej Soriano
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views1 page

CPC07 Object Oriented Programming

The document contains a Java program for calculating the factorial of a positive integer using object-oriented programming principles. It includes error handling for invalid inputs and formats the output for better readability. The program allows the user to input up to five integers and displays the factorial for each valid input.

Uploaded by

Ej Soriano
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

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
}
}

You might also like