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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!