aspose file tools*
The moose likes Beginning Java and the fly likes Loop Qestion Head First pg 63 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Loop Qestion Head First pg 63" Watch "Loop Qestion Head First pg 63" New topic
Author

Loop Qestion Head First pg 63

Tariq Ab
Greenhorn

Joined: Oct 24, 2009
Posts: 14
My question is, why did we initializae the value of z to -1?
Couldn't we just set it to 0 and get it to loop 0 through 2?

Another question, is using the 2 IF statements effecient here? couldn't we just stayed with the while loop statement for the rest array values?

hope my questions make sense and appreciate your help

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38413
    
  23
That is different code from page 63 in my copy of HFJ. My copy has int z = 0;
The answer is not actually correct for the question asked. Both code snippets will compile correctly, but both will suffer an Exception, different in each case. The reason for the -1 is so entering the loop, the index used will be 0. You also have to change the < 4 to < 2 so you never have an index of 3 or greater.

If you cannot see why you need -1, get a pencil and paper. Starting at the line starting "while", write down the value of z, and which element in the array you are dealing with, as you go through the loop.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38413
    
  23
Tariq Ab wrote:. . . Couldn't we just set it to 0 and get it to loop 0 through 2? . . .
Yes, but that would make the exercise too easy. It is supposed to mimic the sort of question you get in certification exams.
The correct form of a for loop to initialise array elements is like this;Notice the only number literal you use is 0.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Loop Qestion Head First pg 63