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

Write a Java program that repeatedly accepts two integers from the keyboard and

ID: 3601182 • Letter: W

Question

Write a Java program that repeatedly accepts two integers from the keyboard and prints the quotient to the console. Your code must adhere to the follow specifications:

The user must enter 0 for both the numerator and denominator to exit the program.

You must read the input values using the Scanner’s next() method and then convert to a primitive integer using Integer.parseInt. In case of an exception (when converting the string to an integer), the program must (1) print the corresponding stack trace(printStackTrace) and (2) reset the Scanner object.

The program must catch division by zero exceptions and print a corresponding message in caseone occurs. The error should not be printed if the user intends to exit.

Explanation / Answer

import java.util.Scanner;

public class Quotient {

public static void main(String[] args) {

Scanner scr=new Scanner(System.in);

int a,b;

//infinite loop for continuous input

while(true){

a=0;b=0;//initialize as default value

if(scr==null){//reinitialize scanner after reset

scr=new Scanner(System.in);

}

try{

a=Integer.parseInt(scr.next());//num1 input using scanner

b=Integer.parseInt(scr.next());//num2 input using scanner

}catch(NumberFormatException e)//Catch exception in case entered value is not a number

{

e.printStackTrace();

scr=null;//reset Scanner

continue;

}

//exit condition

if(a==0 && b==0){

scr.close();//close stream

System.exit(1);//force exit program

}else

//else print the quotient

try{

System.out.println(a/b);

//Catch exception in case divide by 0 occurs

}catch(ArithmeticException ae){

System.out.println("Divide by 0");

}

}

}

}

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