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); } }
Explanation / Answer
a) add the following before your switch statement: try { Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.out.println("Wrong Input: " + args[0]); System.exit(1); } try { Integer.parseInt(args[2]); } catch (NumberFormatException e) { System.out.println("Wrong Input: " + args[2]); System.exit(1); } b) add the following before your switch statement: for (char c : args[0].toCharArray()) { if ((int)c < 48 || (int)c > 57) { System.out.println("Wrong Input: " + args[0]); System.exit(1); } } for (char c : args[2].toCharArray()) { if ((int)c < 48 || (int)c > 57) { System.out.println("Wrong Input: " + args[2]); System.exit(1); } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.