The document contains a Java program that prompts the user to enter a positive integer and validates the input. If the input is valid, it calculates and displays the factorial of the number. The program handles exceptions for invalid inputs and ensures the number is positive before proceeding with the calculation.
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 ratings0% found this document useful (0 votes)
0 views1 page
act3
The document contains a Java program that prompts the user to enter a positive integer and validates the input. If the input is valid, it calculates and displays the factorial of the number. The program handles exceptions for invalid inputs and ensures the number is positive before proceeding with the calculation.
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
import java.util.
Scanner;
public class Activity3 {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number = -1;
// Input validation loop
while (true) { System.out.print("Enter a positive integer: "); try { number = Integer.parseInt(scanner.nextLine()); if (number > 0) { break; } else { System.out.println("Error: Number must be positive."); } } catch (NumberFormatException e) { System.out.println("Error: Invalid input. Please enter a positive integer."); } }
// Factorial calculation long factorial = 1; for (int i = 2; i <= number; i++) { factorial *= i; }
System.out.printf("Factorial of %d is %d\n", number, factorial);