I also have some additional comments about your code. First of all, you have declared p1, p2, and p3 as member fields. However, these variables are only used within the method startGame(). I think it would be best to declare these all as local variables instead. One reason is that as instance variables, the Player objects that you create will not be available for garbage collection because the references to them will exist as long as the GuessGame instance exists. On the other hand, as local variables all the objects will be available for garbage collection as soon as the startGame() method ends. In this particular instance, there is probably no significant difference. However, as you learn to write larger programs, memory management may become an issue that you need to think about. It's a good idea to get into the habit of thinking about such things.
Next, you have the following lines of code:
First of all, I would combine these together to declare the variable at the same time you assign it a value. One reason for this is that 0 is a valid guess that the player may enter. If you happen to forget to assign the actual guess or if you modify the code, it will be difficult to tell if a 0 is from the initial value or if it is a valid guess. So I suggest that you combine this into one line:
Second, I don't see where p1number is declared. Is this supposed to be p1
.number? Since you have not posted the Player class, I don't know if it has a member field called number. Assuming that there is, it will also need public (or perhaps default or protected) access in order for this to compile. However, public member variables are strongly discouraged because it gives other classes access to implementation details. This breaks encapsulation, which is a basic principle of Object Oriented Programming.
If you are allowed to modify the Player class, I suggest that you change p1.guess() to return an int representing the number that the player guesses. This way you can just do
This is a much cleaner way of implementing this since you don't need to know how the player's guess is stored. Also, it avoids the problem of trying to access p1.number before calling p1.guess().
Finally, you have these two lines of code:
Notice that the second line of code is indented. This is not a typical convention. In fact, all the following lines are indented to the same level. This makes the code a little confusing to read. I suggest that you unindent all of the code until the next closing brace.
Well, I hope you are enjoying learning Java. Please keep coming back with more questions. I'll be more than happy to give feedback (whether you ask for it or not
).
Layne