I am currently reading through the 2nd edition of Head First Java. I finished the problems at the end of Chapter 3 and began to manipulate them, seeing what I could change while still yield the same output. My question pertains to the following two problems :
Problem 1 :
Problem 2 :
They both compile and run correctly. However, when I take : out of the while loop, in Problem 2, and place it under: the code does not compile? As apposed to the new objects created outside the while loop in Problem 1 which does compile?
Apart from what has been mentioned already, there are more things to pay attention on:
1. Even tho, if this class is just for a test purpose, please keep in mind when you implement non-test, that instance variables in most cases should be private. Do differently if you have valid reason to do so.
2. Also, name variables so they'd reveal their purpose from the first glance. i.e. variables h, z are not descriptive and self explaining. Such things shouldn't be practiced even in test classes.
3. Don't really understand why you initialize z to -1? and in this matter using while loop which iterates in that way. Shouldn't be easier to use traditional form of for loop and iterate from 0 till ... ?
4. Each Hobbit you name as "bilbo", and later on if it turns out that it is 1 or 2 you rename it accordingly. That is also not very correct. Think of case how to name it once.
5. On lines 10 and 13 you have two if statements. Consider in such cases using else if. Bear in mind, it is going to be either 1 or 2, but never both.
6. Last thing. Try do not cram everything to a main method, as it suppose to start your application only.
If you're gonna buy things, buy this thing and I get a fat kickback: