Java Reference
In-Depth Information
Caution
Don't use floating-point values for equality checking in a loop control. Because floating-
point values are approximations for some values, using them could result in imprecise
counter values and inaccurate results.
Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1 :
double item = 1 ; double sum = 0 ;
while (item != 0 ) { // No guarantee item will be 0
sum += item;
item -= 0.1 ;
}
System.out.println(sum);
Variable item starts with 1 and is reduced by 0.1 every time the loop body is executed.
The loop should terminate when item becomes 0 . However, there is no guarantee that
item will be exactly 0 , because the floating-point arithmetic is approximated. This loop
seems okay on the surface, but it is actually an infinite loop.
numeric error
5.2.5 Input and Output Redirections
In the preceding example, if you have a large number of data to enter, it would be cumbersome
to type from the keyboard. You can store the data separated by whitespaces in a text file, say
input.txt , and run the program using the following command:
java SentinelValue < input.txt
This command is called input redirection. The program takes the input from the file input
.txt rather than having the user type the data from the keyboard at runtime. Suppose the con-
tents of the file are
input redirection
2 3 4 5 6 7 8 9 12 23 32
23 45 67 89 92 12 34 35 3 1 2 4 0
The program should get sum to be 518 .
Similarly, there is output redirection, which sends the output to a file rather than displaying
it on the console. The command for output redirection is:
output redirection
java ClassName > output.txt
Input and output redirection can be used in the same command. For example, the following
command gets input from input.txt and sends output to output.txt :
java SentinelValue output.txt
Try running the program to see what contents are in output.txt .
5.1
Analyze the following code. Is count < 100 always true , always false , or some-
times true or sometimes false at Point A, Point B, and Point C?
Check
Point
int count = 0 ;
while (count < 100 ) {
// Point A
System.out.println( "Welcome to Java!" );
count++;
// Point B
}
// Point C
 
 
Search WWH ::




Custom Search