13.1* ( NumberFormatException ) Listing 9.5 , Calculator.java, is a simple comma
ID: 3550089 • Letter: 1
Question
13.1*
(NumberFormatException) Listing 9.5, Calculator.java, is a simple command-line calculator. Note that the program terminates if any operand is nonnumeric. Write a program with an exception handler that deals with nonnumeric operands; then write another program without using an exception handler to achieve the same objective. Your program should display a message that informs the user of the wrong operand type before exiting (see Figure 13.6).
Calculator.java, is a simple command-line calculator. Note that the program terminates if any operand is nonnumeric. Write a program with an exception handler that deals with nonnumeric operands; then write another program without using an exception handler to achieve the same objective. Your program should display a message that informs the user of the wrong operand type before exiting (see Figure 13.6).Explanation / Answer
With exception handler
import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String option;
do{
try{
System.out.println("****Welcome to calculator*******");
System.out.print("Enter first number:: ");
int first = in.nextInt();
System.out.print("Enter the operator('+','-','*' or '/')::");
String operator = in.next();
System.out.print("Enter second number");
int second = in.nextInt();
double result = 0;
if(operator.equals("+")){
result = first+second;
}
else if(operator.equals("-")){
result = first-second;
}
else if(operator.equals("*")){
result = first*second;
}
else if(operator.equals("/")){
result = first/second;
}
String resultFormatted = String.format("%.2f",result);
System.out.println("Result for "+first+operator+second+" = "+result);
}
catch(InputMismatchException e){
System.err.println("Non numeric value entered");
System.exit(0);
}
System.out.println("Do you want to continue?(Y/N)");
option = in.next();
}
while(option.equalsIgnoreCase("Y"));
in.close();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.