ptg7068951
Exceptions 251
As an introduction to why this is useful, enter the short Java application in
Listing 18.1 in a new empty Java file called Calculatorand save the file.
LISTING 18.1 The Full Text of Calculator.java
1: public classCalculator {
2: public static voidmain(String[] arguments) {
3: floatsum = 0;
4: for (int i = 0; i < arguments.length; i++) {
5: sum = sum + Float.parseFloat(arguments[i]);
6: }
7: System.out.println(“Those numbers add up to “+ sum);
8: }
9: }
The Calculatorapplication takes one or more numbers as command-line
arguments, adds them up, and displays the total.
Because all command-line arguments are represented by strings in a Java
application, the program must convert them into floating-point numbers
before adding them together. The Float.parseFloat()class method in
Line 5 takes care of this, adding the converted number to a variable named
sum.
Before running the application with thefollowing command-line
arguments, which can be set in NetBeans with the Run, Set Project
Configuration, Customize command: 8 6 7 5 3 0 9. Choose Run, Run
Main Project to run the application and see the output in Figure 18.1.
FIGURE 18.1
The output of the Calculator
application.
Run the program several times with different numbers as arguments. It
should handle them successfully, which might make you wonder what this
has to do with exceptions.
To see the relevance, change the Calculatorapplication’s command-line
arguments to 1 3 5x.
The third argument contains a typo—there shouldn’t be an xafter the
number 5. The Calculatorapplication has no way to know this is a mis-
take, so it tries to add 5xto the other numbers, causing the following
exception to be displayed: