Q.Write a java program to accept a number from user, If it is greater than 1000 then throw user defined exception “Number is out of Range” otherwise display the factors of that number. (Use static keyword) [15 M]
import java.util.Scanner;
// User defined exception
class NumberOutOfRangeException extends Exception
{
public NumberOutOfRangeException(String msg)
{
super(msg);
}
}
class FactorDemo
{
// Static method to display factors
static void displayFactors(int n)
{
System.out.println("Factors of " + n + " are:");
for(int i = 1; i <= n; i++)
{
if(n % i == 0)
System.out.print(i + " ");
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
try
{
System.out.print("Enter a number: ");
int num = sc.nextInt();
// Condition check
if(num > 1000)
throw new NumberOutOfRangeException("Number is out of Range");
// Call static method
displayFactors(num);
}
catch(NumberOutOfRangeException e)
{
System.out.println(e.getMessage());
}
}
}