Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help with this Java lab on exception handling! Here are the directions: E

ID: 3763786 • Letter: I

Question

I need help with this Java lab on exception handling!

Here are the directions:

Exception Handling

Lab Assignment

This lab assignment will ask you to write a program that catches exceptions.

Exercise 1

1. Create a New Project named DivideTwo.

2. Cut and paste from the DivideTwo.java file into the DivideTwo class.

3. Enter a zero for the denominator. What exception gets thrown?

4. Modify the program so that it handles the exception thrown in a catch statement when a zero is entered and informs the user.

5. The output should look as follows:

Enter the numerator: 25

Enter the denominator: 5

25/5=5

or

Enter the numerator: 5

Enter the denominator: 0

Cannot divide by zero!

Submit a document with the source code and sample output in Blackboard.

DivideTwo.java

import java.util.*;

public class DivideTwo {

    public static void main(String[] args) {

      Scanner keyboard = new Scanner(System.in);

        System.out.print("Enter the numerator: ");

        int numerator = keyboard.nextInt();

        System.out.print("Enter the denominator: ");

        int denominator = keyboard.nextInt();

        System.out.println(numerator + "/" + denominator

                + "=" + numerator / denominator);

    }

}

Explanation / Answer

import java.util.*;

public class DivideTwo {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter the numerator: ");
        int numerator = keyboard.nextInt();
        System.out.print("Enter the denominator: ");
        try
        {
           int denominator = keyboard.nextInt();
            System.out.println(numerator + "/" + denominator
                    + "=" + numerator / denominator);
        }
        catch(ArithmeticException ae)
        {
           System.out.println("Cannot divide by zero!");
        }

    }

}