• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to call variables from another class and use them?  RSS feed

 
Adam Miszczak
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I have been coding in java for like a week now, but I still have no idea how to call variables from another class:

I have tried using an "accessor method" but it doesn't work, it says it cannot be resolved to a variable:





Thanks in advance!!!
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The error message is telling you exactly what's wrong. You have not declared a variable called monsterhealth in that scope, but you're trying to use that non-existent variable.
 
Adam Miszczak
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did:



It works, but now the value is displayed as zero "Monster now has 0 health"
 
Paul Clapham
Sheriff
Posts: 22844
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Might I suggest



for line 10?

Also, there's no reason to declare that variable at class level. It could perfectly well be a local variable:

 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Adam. Welcome to the Ranch!

Well, it would. You call MonsterSH1Object.getHealth(), which will return 75, but you never assign the value to anything. monsterhealth will be initialised to zero, and then you never try and change it.

would change its value.
 
Adam Miszczak
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the welcome and help guys! It worked perfectly. Thanks again!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!