gpt4 book ai didi

java - 奇怪的运行时错误声明类 Java 的实例

转载 作者:搜寻专家 更新时间:2023-11-01 01:52:07 24 4
gpt4 key购买 nike

我正在用 Java 制作游戏,并且始终遇到最奇怪的错误。我有一类叫做武器。然后我创建了一个名为 primary 的实例。在我创建一个实例并将其称为次要实例之后。由于一些奇怪的原因,主要的被次要的值覆盖。我和导师都看了,想不通。这是代码:

public class weapon {
static String type;
static String name;
static int weight;
static int damage;
static int dodge;
weapon(String c, String n, int w, int da, int dod) {

type = c;
name = n;
weight = w;
damage = da;
dodge = dod;

}
//getters
String getType(){
return type;
}
String getName(){
return name;
}
Integer getWeight(){
return weight;
}
Integer getDamage(){
return damage;
}
Integer getDodge(){
return dodge;
}
//setters
void setType(String c){
c=type;
}
void setName(String n){
n=name;
}
void setWeight(Integer w){
w=weight;
}
void setDamage(Integer da){
damage=da;
}
void setDodge(Integer dod){
dodge=dod;
}
}

/*At the top of my main class I create both instances like this because the instances are created in if statements and I need to access them.*/
weapon primary;
weapon secondary;
//I create primary like this earlier in the code like this
primary = new weapon("primary","sword", 8, 6, -1);
//and then when I run this I get the output "sword" "Heavy Sword".
System.out.println(primary.getName());
secondary = new weapon("secondary", "huge sword", 9, 7, -2);
System.out.println(primary.getName());

最佳答案

你所有的成员变量都定义为静态的:

    static String type;
static String name;
static int weight;
static int damage;
static int dodge;

这就是为什么第二个实例的值会覆盖第一个实例的原因(因为静态成员是类可验证对象 - 在类的所有实例中都有一个副本)。

删除 static 关键字将解决问题。

关于java - 奇怪的运行时错误声明类 Java 的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24811086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com