Java Reference
In-Depth Information
Variable item starts with 1 and is reduced by 0.1 every time the loop body is exe-
cuted. The loop should terminate when item becomes 0 . However, there is no guaran-
tee 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
4.2.5 Input and Output Redirections
In the preceding example, if you have a large number of data to enter, it would be cumber-
some 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
contents 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 < input.txt > output.txt
Try running the program to see what contents are in output.txt .
4.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!\n" );
count++;
// Point B
}
// Point C
4.2
What is wrong if guess is initialized to 0 in line 11 in Listing 4.3?
4.3
How many times are the following loop bodies repeated? What is the printout of each
loop?
int i = 1 ;
while (i < 10 )
if (i % 2 == 0 )
System.out.println(i);
int i = 1 ;
while (i < 10 )
if (i % 2 == 0 )
System.out.println(i++);
int i = 1 ;
while (i < 10 )
if ((i++) % 2 == 0 )
System.out.println(i);
(a)
(b)
(c)
 
Search WWH ::




Custom Search