CJ_Slip_6A

Slip No.6

A) 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)

1. Open Notepad.

2. Type the following code:

    import java.util.Scanner;

    class NumberIsZeroException extends Exception {
    public NumberIsZeroException(String message) {
    super(message);
    }
    }

    public class NumberProcessor {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int number = scanner.nextInt();

    try {
    int result = processNumber(number);
    System.out.println("Sum of first and last digit: " + result);
    } catch (NumberIsZeroException e) {
    System.out.println(e.getMessage());
    }
    }

    public static int processNumber(int number) throws NumberIsZeroException {
    if (number == 0) {
    throw new NumberIsZeroException("Number Is Zero");
    }

    int lastDigit = number % 10;
    int firstDigit = Integer.parseInt(Integer.toString(Math.abs(number)).substring(0, 1));

    return firstDigit + lastDigit;
    }
    }


3. Save the file with the name NumberProcessor.java. Make sure to select "All Files" in the "Save as type" dropdown and add the .java extension manually.

4. Open the Command Prompt.

5. Compile the Java program by typing:
javac NumberProcessor.java

6. Run the compiled Java program by typing:
java NumberProcessor

7. output:
Enter a number: 12345
Sum of first and last digit: 6

No comments:

Post a Comment