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

Here is a snippet of Java code that inputs two integers and divides them: Scanne

ID: 3777730 • Letter: H

Question

Here is a snippet of Java code that inputs two integers and divides them:

Scanner scan = new Scanner(System.in);

int n1, n2;

double r;

System.out.print("Enter first number:");

n1 = scan.nextInt();

System.out.println("Enter second number:");

n2 = scan.nextInt();

r = (double)n1/n2;

Place this code into a try-catch block with multiple catches so that different error messages are printed if we attempt to divide by zero or if the user enters textual data instead of integers (java.util.InputMismatchException). If either of these conditions occurs, then the program should loop back and let the user enter new data.

Explanation / Answer

import java.util.Scanner;
import java.lang.Double;
import java.lang.Integer;

class Ideone
{
   public static void main (String[] args) throws java.lang.Exception
   {
       Scanner scan = new Scanner(System.in);

       int n1, n2;
       double r;
       while(true):
           System.out.print("Enter first number:");
           try {
               n1 = scan.nextInt();
               System.out.println("Enter second number:");
               n2 = scan.nextInt();
           } catch (InputMismatchException e) {
               System.out.println("Wrong Input. try again");
               continue;
           }
           try {
               r = n1/n2;
               r = (double)n1/n2;
               System.out.println(r);
           } catch (ArithmeticException e) {
                System.out.println("ArithmeticException occured!. Try again");
                continue;
            }
            break;
       }
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote