Forums Register Login

constructor running but not having a lasting effect

+Pie Number of slices to send: Send
I'd been wondering why no one was replying to my post asking this on Friday. Because I hadn't actually posted it might be a reason....

Anyway, so I 've written a class which should generate objects which take steps to run a session of a game. To test my code, I wrote a little class with a static main thread which would just try things out and print results. The constructor and fields for the game running class look like this:

and the little test program is

So, if you follow my thinking (and assuming addplayer does what its name implies), it seems that the output should be something like

foo 1
purple 1
true
4
true
Jon
Fred
Susan
Mark

But instead, the output is

foo 1
purple 0
false
3
false
Fred
Susan
Mark


So... am I missing something obvious? Why does the testing program output a value of 1 for game.numberOfPlayers=0 when the constructor set numberOfPlayers=1?

Any ideas?
+Pie Number of slices to send: Send
 

J R Hatch wrote:So... am I missing something obvious? Why does the testing program output a value of 1 for game.numberOfPlayers=0 when the constructor set numberOfPlayers=1?



I guess it isn't obvious, because a lot of Java beginners do the same thing. Your constructor assigns 1 to a local variable named "numberOfPlayers". It leaves the instance variable "numberOfPlayers" untouched because the local variable hides that.

So don't declare those local variables in your constructor. What you did for "playerList" is the right thing to do.
1
+Pie Number of slices to send: Send
Because this line:

is creating a variable named numberOfPlayers in the constructor which occludes the instance variable.

[Edit: beat by 20 seconds!]
+Pie Number of slices to send: Send
 

Paul Clapham wrote:

J R Hatch wrote:So... am I missing something obvious? Why does the testing program output a value of 1 for game.numberOfPlayers=0 when the constructor set numberOfPlayers=1?



I guess it isn't obvious, because a lot of Java beginners do the same thing. Your constructor assigns 1 to a local variable named "numberOfPlayers". It leaves the instance variable "numberOfPlayers" untouched because the local variable hides that.

So don't declare those local variables in your constructor. What you did for "playerList" is the right thing to do.



You and Bear are awesome except for making me feel dumb. Thanks.
Ew. You guys are ugly with a capital UG. Here, maybe this tiny ad can help:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 953 times.
Similar Threads
2 methods into one?
What's the problem here?
array out of bounds exception problem
OOP basic question for an old newbie
error: "cannot find symbol"
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 05:38:55.