Java Reference
In-Depth Information
// Declare and initialize three variables
int numOranges = 5; // Count of oranges
int numApples = 10; // Count of apples
int numFruit = 0; // Count of fruit
numFruit = numOranges + numApples; // Calculate the total fruit
count
// Display the result
System.out.println("A totally fruity program");
System.out.println("Total fruit is " + numFruit);
// Code to delay ending the program
System.out.println("(press Enter to exit)");
try {
System.in.read();
// Read some input from the
keyboard
} catch (IOException e) {
// Catch the input exception
return;
// and just return
}
}
}
code snippet FruitWait.java
I have changed the class name from Fruit to FruitWait to distinguish it from the previous version of
the program. The file FruitWait.java is in the code download for the topic. I won't go into this extra
code here. If you need to, just put it in for the moment. You will learn exactly how it works later in the
book.
How It Works
The stuff between the parentheses following main — that is String[] args — provides a means of ac-
cessing data that passed to the program from the command line when you run it. I go into this in detail
later in the topic so you can just ignore it for now, though you must always include it in the first line of
main() . If you don't, the program compiles but doesn't execute.
All that additional code in the body of the main() method in the FruitWait.java version just waits
until you press Enter before ending the program. If necessary, you can include this in all of your console
programs at each point in the code where the program terminates to make sure they don't disappear be-
fore you can read the output. It won't make any difference to how the rest of the program works. I will
defer discussing in detail what is happening in the bit of code that I have added until I get to explaining
exceptions in Chapter 7.
If you run the FruitWait.java version of this program, the output is the following:
A totally fruity program
Total fruit is 15
(press Enter to exit)
The original version does not output the third line.
The basic elements of the code in the original version of the program are shown in Figure 2-2 :
FIGURE 2-2
 
 
Search WWH ::




Custom Search