JAVA . “AnInputMismatchExceptionisthrownbyaScannertoindicatethatthetokenretrieve
ID: 3671360 • Letter: J
Question
JAVA
. “AnInputMismatchExceptionisthrownbyaScannertoindicatethatthetokenretrieved does not match the pattern for the expected type, or that the token is out of range for the expected type”. For example, if you use the nextDouble to read a token that is not of the type double.
Write a program that prompts the user to enter a mathematical formula (e.g., 4.3 + 5.1) and then displays the result. Your program should prompt the user to try again if the input has an invalid number or invalid operator (i.e., valid operators are: +, -, /, and *). Assume the user enters spaces between the operands and the operator. Read the numbers using the Scanner’s nextDouble method, and the operator using the next method.
Hints: Use a while loop that will keep prompting the user for input as long as it is invalid. Use a try-catch statement to check for the numbers’ validity. Use a selection statement (e.g., if, switch, etc.) to check for the operator’s validity.
Explanation / Answer
import java.util.InputMismatchException;
import java.util.Scanner;
public class Except {
public static void main(String[] args) {
System.out.println("Program for Addition, Subtraction, Multiplication and Division ");
Scanner input = new Scanner(System.in);
double a,b,result;
char opcode;
/*in the try block check the exception for input is double or not until user enters double value*/
while(true)
{
try {
System.out.println("Enter first number ");
a = input.nextDouble();
System.out.println("Enter second number");
b = input.nextDouble();
}
catch (Exception e) {
System.out.println("InputMisMatchException!!!please enter double value");
}
}
/*The while loop executes until user enter valid arithmetic operator i.e +,-,*,/; */
while (true)
{
System.out.println("Enter Your Choice: + for Add, - for Sub,* for Mul, / for Div: ");
opcode = input.nextChar();
switch (opcode)
{
case '+':
result = a + b;
System.out.println("Addition of numbers is"+ result);
break;
case '-':
result = a - b;
System.out.println("Subtraction of numbers is"+ result);
break;
case '*':
result = a * b;
System.out.println("Multiplication of numbers is"+ result);
break;
case '/':
result = a / b;
System.out.println("The division between two numbers is"+ result);
break;
default:
System.out.println("Try again !! Please enter valid number");
return;
}
}
}//main
}//class
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.