Reputation: 5
import java.util.Scanner;
class player_test {
public static void main(String[] args) {
Scanner s_in = new Scanner(System.in);
Scanner i_in = new Scanner(System.in);
class player {
String player_name;
String player_class;
String player_race;
int player_STR = 10;
int player_DEX;
int player_CON;
int player_WIS;
int player_INT;
int player_CHA;
}
int tempDex = new player(player_STR);
System.out.println(tempDex);
}
}
Alright, so I'm pretty new to java and I think this is more basic than I am making it out to be. So I have object player, that stores the player core stats in it, but how do I call on those variables at other points throughout the code? At least make it print the players strength score?
Upvotes: 0
Views: 140
Reputation: 2508
since all the variables in class player are non-static,so you need to create the object of this class to access its non-static data members.
int tempDex=new player(player_STR); //this will generate compilation error
Here you are creating a object of player class.so you should keep the tempDex of player type (can be super class too). Secondly,you are using a parameterized constructor which is not defined in the class.So the proper way to do it is like this.....
player tempDex=new player(); // an Object of class player is created
System.out.println(tempDex.player_STR);
System.out.println(tempDex.player_Name);
// and so on.
Upvotes: 1
Reputation: 26926
The best practice is to create public methods that expose the internal state of your object that should be visible from other classes and leave not visible informations that should not be used by other classes.
Generally those methods are called getters and use the following syntax:
public String getPlayer_name() {
return player_name;
}
Then in the second class you can print it very simply:
// is a best practice to start class names with uppercase
Player x = new Player();
... // Do something
System.out.println(x.getPlayer_name());
Upvotes: 2