Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variables from another class won't assign to main class

 
brent carter
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys. Simple program and my variables are not recognized in the main even after calling them for assignment. When I try to print out the assigned Health, Strength etc variables in Line 20 it says they are not assigned. What am i doing wrong?

 
fred rosenberger
lowercase baba
Bartender
Posts: 12122
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no "Health" variable in scope in your main() method. Now, the Mage instance you have created has one defined. So, in line 20, tell it to print that:



Now, your code has several other issues, but this will get you past this first problem.
 
brent carter
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks for the reply fred. I tried this and it still said the same thing.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12122
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ah...I didn't look at your code close enough.

also, it would help if you would post the EXACT and COMPLETE text of what the error is. "not assigned" is different from "cannot find".

the problem is that your variables don't exist. look at your Mage class. You have nothing but a Magestats method. Inside that method, you declare the variables. That means those variable are local to that method. Once the method ends, the variables essentially disappear. You need to declare them as member variables...like this:


Now the variables belong to each instance of the class. So, you can create 30 Mages, and each will have their own health, strength, etc.


A couple of notes....Classes should start with a capital letter. variables and such should start with a lower-case letter. So, your line

really should be

and then the appropriate edits in your main method.

In a similar fashion, your Strength variable should really be named "strength".

There are a lot of other things we could talk about to make your code cleaner, but we'll worry about those another day.
 
brent carter
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wow thanks for the nice reply. I've been on several different forums and no one answered me. I made the fixes and it worked.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic