Java Reference
In-Depth Information
LISTING 7.2
Continued
10: }
11:
12: public static void main(String[] arguments) {
13: if (arguments.length < 2) {
14: System.out.println(“Usage: java CalorieCounter calories fat
fiber”);
15: System.exit(-1);
16: }
17: try {
18: int calories = Integer.parseInt(arguments[0]);
19: int fat = Integer.parseInt(arguments[1]);
20: int fiber = Integer.parseInt(arguments[2]);
21: CalorieCounter diet = new CalorieCounter(calories, fat, fiber);
22: System.out.println(“Adjusted calories: “ + diet.count);
23: } catch (NumberFormatException nfe) {
24: System.out.println(“All arguments must be numeric.”);
25: System.exit(-1);
26: }
27: }
28: }
The CalorieCounter application calculates an adjusted calories total for a food item
using its calories, fat grams, and fiber grams as input. Programs like this are common in
weight management programs, enabling dieters to monitor their daily food intake.
The application takes three command-line arguments: calories, fat, and fiber, which are
received as strings and converted to integer values in lines 18-20.
The CalorieCounter constructor takes the three values and plugs them into a formula in
line 8 to produce an adjusted calorie count.
One of the assumptions of the constructor is that the adjusted count always will be a pos-
itive value. This is challenged with the following assert statement:
assert count > 0 : “Adjusted calories < 0”;
The compiled class should be run with the -ea flag to employ assertions, as in this
example:
java -ea CalorieCounter 150 3 0
Those values produce an adjusted calorie count of 3.25. To see the assertion proven false,
use 30 calories, 0 grams of fat, and 6 fiber as input.
 
Search WWH ::




Custom Search