在我的Player.java对象类中,我有以下代码
private static int playerAge;
与
playerAge = 18;
在我的构造方法
public static int getplayerAge() {
return playerAge;
}
但是当试图让我的java类中的玩家年龄扩展活动时,它总是显示“0”而不是“18”,就像它应该的那样。这是我的代码。
TextView playerAge = (TextView) findViewById(R.id.tvPlayerAge);
playerAge.setText("Age: " + Integer.toString(Player.getplayerAge()));
我做错了什么?谢谢!
顺便说一下,如果我将private static int playerAge;
从最顶层更改为
private static int playerAge = 18;
它有效,只是不明白为什么它不能从构造函数方法中起作用。
Player.java类
public class Player extends Object {
//Instance Data
private static String playerName;
private static int playerAge = 1;
private static boolean sterile;
//Default Constructor
public Player() {
playerName = "";
playerAge = 5; //For some reason you have to inetiate the playerAge in the instance data for
//it to be able to read it...
sterile = true; //Default Value
}
//Constructor
public Player(String pName, int pAge, boolean isSterile) {
playerName = pName;
playerAge = pAge;
sterile = isSterile;
}
//Accessor Methods (Getters)
public static String getplayerName() {
return playerName;
}
public static int getplayerAge() {
return playerAge;
}
public static boolean getplayerDiseasedState() { //Sterile or not?
return sterile;
}
//Mutator Methods (Setters)
public static void setPlayerName(String name) {
playerName = name;
}
public static void setplayerAge(int age) {
playerAge = age;
}
public static boolean setSterileState(boolean diseased) {
return sterile = diseased;
}
//toString (Accessor)
public String toString() {
String toString = "Player Name: "+ playerName + "\n" +
"Player Age: " + playerAge + "\n" +
"Player Diseased: " + sterile + "\n";
return toString;
}
}
答案 0 :(得分:1)
您不需要Integer.toString()位。只需使用:
player.setText("Age: " + Player.getPlayerAge());