Listing 9.5, Calculator.java, is a simple command line calculator. Note that the
ID: 3620926 • Letter: L
Question
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. Example: Look at picture. Calculator.java: public class Calculator { /** Main method */ public static void main(String[] args) { // Check number of strings passed if (args.length != 3) { System.out.println( "Usage: java Calculator operand1 operator operand2"); System.exit(0); }// The result of the operation int result = 0;
// Determine the operator switch (args[1].charAt(0)) { case '+': result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]); break; case '-': result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]); break; case '*': result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]); break; case '/': result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]); }
// Display result System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result); } }