[英]Java: object cannot be resolved to a variable
my object apparently can't be resolved to a variable... 我的对象显然无法解析为变量...
In Game.Java: 在Game.Java中:
public static void main(String[] args) {
Slime slime = new Slime();
}
In Player.Java: 在Player.Java中:
public static void Attack() {
System.out.println("Player attacks!");
int dmg = ATTACK;
System.out.println(dmg + " damage to Slime!");
slime.HP -= dmg;
System.out.println(Player.HP);
}
So how do I take dmg off of slime's HP? 那么,我该如何从史莱姆的HP中移除dmg? I've done some research, this still isn't making sense. 我已经做了一些研究,但这仍然没有道理。
Player.java needs to either have a reference to slime, or it needs to be passed in through the Attack() method. Player.java需要引用史莱姆,或者需要通过Attack()方法传递它。 The second makes more sense, actually. 实际上,第二个更有意义。
public void attack(Slime opponent) {
int dmg = ATTACK;
opponent.HP -= dmg;
}
This will allow you to "attack" multiple different slimes. 这将允许您“攻击”多个不同的史莱姆。
The alternative would be to store a reference to the slime in the Player class itself: 另一种方法是将对史莱姆的引用存储在Player类本身中:
public class Player {
private Slime slime;
private static final int ATTACK = 10; // or something
public void setSlime(Slime slime) {
this.slime = slime;
}
public void attack() {
int dmg = ATTACK;
slime.HP -= dmg;
}
}
Effectively, unless you give Player some way of knowing about the Slime instance, it can't affect that Slime instance. 实际上,除非您为Player提供一些了解Slime实例的方法,否则它不会影响该Slime实例。
I did notice that you were using mostly static methods, but here I've used class variables and non-static methods for OOP purposes. 我确实注意到您使用的大多数是静态方法,但是在这里我出于OOP的目的使用了类变量和非静态方法。
Also, Java coding convention is that method calls should have lower case names, which is why I've preferred attack()
to Attack()
. 此外,Java编码惯例是,方法调用应该有小写的名字,这就是为什么我首选attack()
来Attack()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.