Question
Create a Java program.This is a simple try-catch exercise. The program asks for two numbers and returns the product of the two numbers. The program
Create a Java program.This is a simple try-catch exercise. The program asks for two numbers and returns the product of the two numbers. The program works as it is but if someone enters a word instead of a number, the program crashes. Add a try and catch to the existing code that looks for an InputMismatchException and prints out "A Non-Number value was entered." .
I have this code but it does not run in the compiler I need to use for the assignment.It states it contains an infinite loop:
import java.util.*;
public class InputMismatchCatch {
public static void main(String[] args) { int x=0; Scanner input = new Scanner(System.in);
do{ try{ input = new Scanner(System.in); System.out.println("This program accepts two numbers" + " and returns the product. The first number " + "will be multiplied by the second one Please enter " + "the first number:"); double num1 = input.nextDouble(); System.out.println("Please enter the second number:"); double num2 = input.nextDouble(); System.out.printf("%s multiplied by %s equals %s", num1,num2,(num1*num2)); x=1;
} // end main class catch(InputMismatchException e){ System.out.println(" Non-Number value was entered."); input.next();
}
}while(x==0); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started