Slip No 6 Q A

Q.Write a java program to accept a number from user, if it zero then throw user defined Exception “Number Is Zero”, otherwise calculate the sum of first and last digit of that number. (Use static keyword). [ 15 M]

import java.util.Scanner;

// User defined exception
class NumberZeroException extends Exception {
    NumberZeroException(String msg) {
        super(msg);
    }
}

public class FirstLastSum {

    // Static method to calculate sum of first and last digit
    static int sumFirstLast(int num) {
        int last = num % 10;
        int first = num;

        while(first >= 10) {
            first = first / 10;
        }

        return first + last;
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();

        try {
            if(n == 0) {
                throw new NumberZeroException("Number Is Zero");
            }

            int sum = sumFirstLast(Math.abs(n));
            System.out.println("Sum of first and last digit = " + sum);

        } catch(NumberZeroException e) {
            System.out.println("Exception: " + e.getMessage());
        }

        sc.close();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top