In: Computer Science
__________________________________________________________________________
The Calculator.java code
1: package com.java24hours;
2:
3: public class Calculator {
4: public static void main(String[] arguments) {
5: float sum = 0;
6: for (String argument : arguments) {
7: sum = sum + Float.parseFloat(argument);
8: }
9: System.out.println("Those numbers add up to " + sum);
10: }
11: }
__________________________________________________________________________
The NewCalculator.java code
1: package com.java24hours;
2:
3: public class NewCalculator {
4: public static void main(String[] arguments) {
5: float sum = 0;
6: for (String argument : arguments) {
7: try {
8: sum = sum + Float.parseFloat(argument);
9: } catch (NumberFormatException e) {
10: System.out.println(argument + " is not a number.");
11: }
12: }
13: System.out.println("Those numbers add up to " + sum);
14: }
15: }
//if you are satisfied with the answer kindly leave a like, comment to clear doubts
1. In Calculator.java it leads to an error since "5x" cannot be float parsed hence it gives an error. There is no float value corresponding to "5x" like "8" is 8.0 and "1" is 1.0
2. Exception handling is a better programming technique since while deploying applications, it may lead to the application crashing and pausing the whole process of working on the application and leads to bad user experience.
Handling errors leads to a smooth flow of programs.
Screenshot:
Calculator.java:
NewCalculator.java: