Wrote a program called ExceptionalDivide that asks the user for 2 integer values
ID: 3721855 • Letter: W
Question
Wrote a program called ExceptionalDivide that asks the user for 2 integer values and displays the quotient of the first value divided by the second value. Make sure the your program reads in the two input values as ints. Your program must catch either of two exceptions that might arise and crash your program
java.util.InputMismatchException //wrong data type inputted
java.lang.ArithmeticException //divide by zero error
Once you catch these exceptions, your program must print out a message explaining what happened and then ask the user to re-enter both inputs. Also, the program must catch these exceptions repeatedly if the user keeps inputting invalid values. When valid values are entered, the program prints the quotient and ends. Write the entire program, including the class statements, the main method declaration, and any import statements you may need.
Explanation / Answer
import java.util.Scanner;
import java.util.InputMismatchException;
public class ExceptionalDivide {
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int num1=0,num2 =0;
boolean isValid = false;
while(!isValid) {
try{
System.out.println("Enter the first integer:");
num1 = scan.nextInt();
isValid= true;
}catch(InputMismatchException e1){
System.out.println("Invalid Input. Please enter again.");
}
}
isValid=false;
while(!isValid) {
try{
System.out.println("Enter the second integer:");
num2 = scan.nextInt();
double q= num1/num2;
System.out.println("Quotient is "+q);
isValid= true;
}catch(InputMismatchException e1){
System.out.println("Invalid Input. Please enter again.");
}
catch(ArithmeticException e2){
System.out.println("Invalid Input. Divisort must be greater than 0");
}
}
}
}
Output:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.