aspose file tools*
The moose likes Beginning Java and the fly likes Variables from another class won't assign to main class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variables from another class won Watch "Variables from another class won New topic
Author

Variables from another class won't assign to main class

brent carter
Ranch Hand

Joined: Dec 15, 2011
Posts: 34
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

Joined: Oct 02, 2003
Posts: 11499
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
brent carter
Ranch Hand

Joined: Dec 15, 2011
Posts: 34
thanks for the reply fred. I tried this and it still said the same thing.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  16

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

Joined: Dec 15, 2011
Posts: 34
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Variables from another class won't assign to main class