Variables from another class won't assign to main class
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?
Code:
package rpgmain;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
System.out.println("Welcome to Earthbound!");
Scanner chooser = new Scanner(System.in);
System.out.println("Do you want to be a fighter (1) or mage (2)?");
int Charpick;
Charpick = chooser.nextInt();
if (Charpick == 1){
Fighter Fighter1 = new Fighter();
Fighter1.Fighterstats();
System.out.println("You have chosen: Fighter");
}else{
Mage Mage1 = new Mage();
Mage1.Magestats();
System.out.println("You have chose: Mage");
System.out.println("Health: "+ Health +" Magic: "+Magic+" Strength: "+Strength+" Heal: "+Heal);
}
}
}
package rpgmain;
public class Mage {
public void Magestats(){
int Health, Strength, Magic, Heal;
Health = 50;
Strength = 5;
Magic = 25;
Heal = 10;
}
}
package rpgmain;
public class Fighter {
public void Fighterstats(){
int Strength, Health, Magic, Heal;
Strength = 20;
Health = 100;
Magic = 10;
Heal = 5;
}
}
Re: Variables from another class won't assign to main class
The compiler has no clue what those variables are, as they loose scope once the called methods exit. Suggested reading:
Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
Re: Variables from another class won't assign to main class
dowhile thanks for the reply. I am still not clear after reading that site what to do. How do I bring the scope of the variables into the main?
Re: Variables from another class won't assign to main class
Quote:
Originally Posted by
erthbound0
dowhile thanks for the reply. I am still not clear after reading that site what to do. How do I bring the scope of the variables into the main?
One answer is in the first example in the link: create instance variables/fields in your classes. In the first example in the link, this would be cadence, gear, etc...