Problem

(NumberFormatException) Listing 1, Calculator.java, is a simple commandline calculator. No...

(NumberFormatException) Listing 1, 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 1).

FIGURE 1 The program performs arithmetic operations and detects input errors.

LISTING 1 Calculator.java

1 public class Calculator {

2 /** Main method */

3 public static void main(String[] args) {

4 // Check number of strings passed

5 if (args.length != 3) {

6 System.out.println(

7 "Usage: java Calculator operand1 operator operand2");

8 System.exit(0);

9 }

10

11 // The result of the operation

12 int result = 0;

13

14 // Determine the operator

15 switch (args[1].charAt(0)) {

16 case '+': result = Integer.parseInt(args[0]) +

17 Integer.parseInt(args[2]);

18 break;

19 case '-': result = Integer.parseInt(args[0]) -

20 Integer.parseInt(args[2]);

21 break;

22 case '.': result = Integer.parseInt(args[0]) *

23 Integer.parseInt(args[2]);

24 break;

25 case '/': result = Integer.parseInt(args[0]) /

26 Integer.parseInt(args[2]);

27 }

28

29 // Display result

30 System.out.println(args[0] + ' ' + args[1] + ' ' + args[2]

31 + " = " + result);

32 }

33 }

Step-by-Step Solution

Request Professional Solution

Request Solution!

We need at least 10 more requests to produce the solution.

0 / 10 have requested this problem solution

The more requests, the faster the answer.

Request! (Login Required)


All students who have requested the solution will be notified once they are available.
Add your Solution
Textbook Solutions and Answers Search
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT