Monday, 6 November 2023

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)

 

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)   

 

class NumberOutOfRangeException extends Exception {

    public NumberOutOfRangeException(String message) {

        super(message);

    }

}

 

public class FactorsCalculator {

    public static void main(String[] args) {

        try {

            int number = 1200; // Replace with the number you want to check

 

            if (number > 1000) {

                throw new NumberOutOfRangeException("Number is out of Range");

            } else {

                System.out.println("Factors of " + number + ":");

                displayFactors(number);

            }

        } catch (NumberOutOfRangeException e) {

            System.err.println(e.getMessage());

        }

    }

 

    public static void displayFactors(int number) {

        for (int i = 1; i <= number; i++) {

            if (number % i == 0) {

                System.out.println(i);

            }

        }

    }

}