*12.1 (NumberFormatException) Listing 7.9, Calculator.java, is a simple commandl
ID: 3762359 • Letter: #
Question
*12.1 (NumberFormatException) Listing 7.9, Calculator.java, is a simple commandline
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 12.12).
Calculator.java
package chapter7;
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
program with exception handler
program without exception handler:
package NFE2;
import java.util.Scanner;
public class Calculator {
/** Main method */
public static void main(String[] args){
String num1;
String num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("Please enter number1");
num1 = input.next();
int i = Integer.parseInt(num1);
System.out.println("Please enter second number");
num2 = input.next();
int j = Integer.parseInt(num2);
// Check number of strings passed
if (i != (int) i || j != (int) j ){
System.out.println("wrong input");
System.exit(0);
}else{
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+")){
System.out.println("your answer is " + (i + j));
}
if (operation.equals("-"))
{
System.out.println("your answer is " + (i - j));
}
if (operation.equals("/"))
{
System.out.println("your answer is " + (i / j));
}
if (operation .equals( "*"))
{
System.out.println("your answer is " + (i * j));
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.