Java Reference
In-Depth Information
LISTING 4.4
Continued
16: System.out.print(array2[count++] + “ “);
17: }
18: System.out.println(“]”);
19: }
20: }
The output of the program is as follows:
array1: [ 7 4 8 1 4 1 4 ]
array2: [ 7.0 4.0 8.0 ]
Here is what's going on in the main() method:
Lines 3-4 declare the arrays; array1 is an array of integers, which are initialized to
some suitable numbers. array2 is an array of floating-point numbers that is the
same length as array1 but doesn't have any initial values.
n
Lines 6-10 are for output purposes; they simply iterate through array1 using a for
loop to print out its values.
n
Lines 13-17 are where the interesting stuff happens. This bunch of statements both
assigns the values of array2 (converting the numbers to floating-point numbers
along the array) and prints it out at the same time. You start with a count variable,
which keeps track of the array index elements. The test in the while loop keeps
track of the two conditions for exiting the loop, where those two conditions are
running out of elements in array1 or encountering a 1 in array1 . (Remember, that
was part of the original description of what this program does.)
You can use the logical conditional && to keep track of the test; remember that &&
makes sure that both conditions are true before the entire expression is true . If
either one is false , the expression returns false and the loop exits.
n
The program's output shows that the first four elements in array1 were copied to
array2 , but there was a 1 in the middle that stopped the loop from going any further.
Without the 1 , array2 should end up with all the same elements as array1 .
If the while loop's test initially is false the first time it is tested (for example, if the first
element in that first array is 1 ), the body of the while loop will never be executed. If you
need to execute the loop at least once, you can do one of two things:
Duplicate the body of the loop outside the while loop.
n
Use a do loop (which is described in the following section).
n
The do loop is considered the better solution of the two.
 
Search WWH ::




Custom Search