• Post Reply Bookmark Topic Watch Topic
  • New Topic

pass in variable not recognized  RSS feed

 
Ted Schrey
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would anyone know why the integer this.moves is not seeming to pass into my Player Object? this.moves was passed into the first Object from the main as a number (ex: 14). If I do a print, I see it got passed in correctly. Now when I try to re-pass it into the next Object during instantiation, if I do a print in the second Object, it is 0 (14 not passed in). If I type 14 in the parameters of the first object passing to the second, the second then recognizes the 14. Is there something about passed in values that can't be re-passed?

The main passed 14 into the Dungeon object as variable "moves" (this.moves in Dungeon).

I then create Player object and want to pass this.moves into it: Player player = new Player(this.moves);

However, in Player, when I check the pass-in w/i the Constructor, I get a print of 0.



[fixed code tags]
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ted,
Cna you show a main method that behaves as you describe. I'm not following it and your code looks fine.
 
Ted Schrey
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the Main method...




and here is the first part of Dungeon object. the print of moves in the run() gives the correct 14, but when I use this same variable in creating the Player, I get 0 as the print in player ("A: " + moves)...or if I print this.moves in Player, still 0.

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37462
537
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I've simplified your example to illustrate what's going on. The gist of it is that you have both constructor and an instance initializer.

Since the instance initializer runs first, moves is still zero. The solution is to move the Player initialization into that constructor.

in instance initializer
A: 0
in constructor


 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why have you got that instance initialiser in the first place? Why are you not initialising the object entirely in the constructor?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!