如何从封装变量设置文本
How to set text from encapsulated variable
我已将此代码放入新的 class
public class Monster {
private String name;
private int health, mana, attack;
public void setName(String name) {this.name=name;}
public void setHealth(int health) {this.health=health;}
public void setMana(int mana){this.mana=mana;}
public void setAttack(int attack){this.attack=attack;}
public String getName() {return name;}
public int getHealth() {return health;}
public int getMana() {return mana;}
public int getAttack(){return attack;}
public Monster(String name, int health, int mana, int attack) {
}
并想在不同的 activity 中使用它。我确保在 activity 中导入 class 并编写了这些代码:
Monster vampire = new Monster("Vampire", 2000, 300, 25);
我想根据写的内容设置文本视图所以我写了:
monsterName.setText(String.valueOf(vampire.getName()));
monsterHP.setText(String.valueOf(vampire.getHealth()));
monsterMP.setText(String.valueOf(vampire.getMana()));
但是当我 运行 应用程序时,文本视图写入 'null' 并且 monsterHP 和 monsterMP 写入“0”。如何根据class设置文字?
自定义构造函数未正确初始化。
当调用 Monster vampire = new Monster("Vampire", 2000, 300, 25);
时没有设置任何值,所以很明显 null:string
和 0:numbers
returns(java 默认初始化程序)。
适应于:
public Monster(String name, int health, int mana, int attack) {
this.name = name;
this.health = health;
this.mana = mana;
this.attack = atack;
}
我已将此代码放入新的 class
public class Monster {
private String name;
private int health, mana, attack;
public void setName(String name) {this.name=name;}
public void setHealth(int health) {this.health=health;}
public void setMana(int mana){this.mana=mana;}
public void setAttack(int attack){this.attack=attack;}
public String getName() {return name;}
public int getHealth() {return health;}
public int getMana() {return mana;}
public int getAttack(){return attack;}
public Monster(String name, int health, int mana, int attack) {
}
并想在不同的 activity 中使用它。我确保在 activity 中导入 class 并编写了这些代码:
Monster vampire = new Monster("Vampire", 2000, 300, 25);
我想根据写的内容设置文本视图所以我写了:
monsterName.setText(String.valueOf(vampire.getName()));
monsterHP.setText(String.valueOf(vampire.getHealth()));
monsterMP.setText(String.valueOf(vampire.getMana()));
但是当我 运行 应用程序时,文本视图写入 'null' 并且 monsterHP 和 monsterMP 写入“0”。如何根据class设置文字?
自定义构造函数未正确初始化。
当调用 Monster vampire = new Monster("Vampire", 2000, 300, 25);
时没有设置任何值,所以很明显 null:string
和 0:numbers
returns(java 默认初始化程序)。
适应于:
public Monster(String name, int health, int mana, int attack) {
this.name = name;
this.health = health;
this.mana = mana;
this.attack = atack;
}