我有2个按钮,其中1个用于round1rock的构造函数类,而其他1个试图访问这些参数。我的代码有什么问题?
构造函数类
public ROCK(int hp, int stamina, int attack, int speed, String type){
this.hp=hp;
this.stamina= stamina;
this.attack= attack;
this.speed = speed;
this.type = type;
}
2个按钮:
private void continueRound1 (ActionEvent event){
ROCK round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
private void Attack (ActionEvent event){
round1Rock.hp = 12;
}
我如何访问以前制作的对象?
答案 0 :(得分:3)
定义时
private void continueRound1 (ActionEvent event){
ROCK round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
您正在仅为函数ROCK round1Rock
定义continueRound1
。
为了使Attack
访问该对象,您需要在类级别定义round1Rock
。
尝试:
ROCK round1Rock = null;
private void continueRound1 (ActionEvent event){
round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
private void Attack (ActionEvent event){
round1Rock.hp = 12;
}
答案 1 :(得分:0)
在课程级别上定义round1Rock,
class someclass
{
private ROCK round1Rock;
-----
private void continueRound1 (ActionEvent event){
round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
private void Attack (ActionEvent event){
round1Rock.hp = 12;
}
------
}
答案 2 :(得分:0)
首先像这样将ROCK实例声明为全局
private ROCK round1Rock = null;
private void continueRound1 (ActionEvent event){
round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
private void Attack (ActionEvent event){
round1Rock.hp = 12;
}
在Attack动作侦听器中的第二件事,您可能无法访问变量hp,因为它可能是私有的,因此最好为Rock类创建setter和getter方法,然后使用它。
岩石舱:
public ROCK(int hp, int stamina, int attack, int speed, String type){
this.hp=hp;
this.stamina= stamina;
this.attack= attack;
this.speed = speed;
this.type = type;
}
public void setHP(int hp){
this.hp = hp
}
public void getHP(){
return hp;
}
然后在您的其他班级中使用此:
private void Attack (ActionEvent event){
round1Rock.setHP(12); //this will update the value
}
答案 3 :(得分:0)
而不是在continueRound1方法中创建新的Rock对象。您可以在类范围内创建新的Rock对象,并设置私有访问权限。这样可以解决您的问题。
其他提示:您将在每次单击按钮时创建一个新对象。如果我编写一个程序来无限期地单击按钮,这将导致 OutOfMemoryError 。
以下是我避免此问题的见解:
这是我的代码段:
Class Client {
private Rock round1Rock = new Rock();
Client() {
round1Rock = round1Rock.getDefaultRockForType("Metamorphic");
}
private void continueRound1 (ActionEvent event){
round1Rock= round1Rock.getDefaultRockForType("Metamorphic");
}
private void Attack (ActionEvent event){
round1Rock.setHp(12);
}
}
在Rock类中,您可以根据岩石类型提供默认值。
摇滚巨人:
public Rock getDefaultRockForType(String type){
if(type.equals("Metamorphic")){
this.hp=500;
this.stamina= 100;
this.attack= 100;
this.speed = 100;
this.type = type;
}
}