java - 为什么这些 Character 对象不保留特征?
问题描述
我正在为我的 AP Comp Sci 课程编写一个基本的 RPG。对于这个问题,唯一重要的两个类是 Character 和 Client。客户端运行一切,而 Character 具有许多传统上角色应具有的属性。
问题:我正在创建一个名为 Character 的类的 2 个不同实例。但是,当我尝试使用 toString() 方法打印它们时,只会打印最近实例化的一个。
尝试过的解决方案我尝试在其他类中编写 toString() 方法,并使用 Character 作为参数,我在谷歌上搜索了这个问题,但没有发现任何类似的东西。还尝试放置“这个”。在 toString() 方法中的变量前面。
编码
客户端类
import java.util.*;
public class Client{ //change to client
public static void main(String[] args){
Character NPC = new Character("Neil", 2, 20); //instance 1
Character mainChar = new Character("Alfred", 3, 18); //instance 2
System.out.println(mainChar.toString()); //PROBLEM
System.out.println(NPC.toString()); //PROBLEM
}
}
字符类
import java.util.*;
public class Character{
public static String name; //name in gameplay, not in program
public static int type; //1) tank, 2) range, 3) magic
public static int hp; //health
public static int age; //age
public static int dmg; //avg. damage per attack
public static int dmgMod; //+/- from dmg
public static Item[] inventory = new Item[10]; //array of different things. Item is another class
public Character(String name, int type, int age){
int modify = new Random().nextInt(3);
inventory[0] = new Weapon("Fists");
this.name = name;
this.type = type;
this.age = age;
this.hp = age * 15;
this.dmg = 0; // ***
this.dmgMod = 2 + (int)(this.age / 10) + modify;
}
//THIS is where the issue happens
public String toString(){
return "\nName: " + name + "\n" +
"Class: " + type + "\n" +
"Age: " + age + "\n" +
"HP: " + hp + "\n" +
"Damage: " + dmg + "\n" +
"Damage Modifier: " + dmgMod;
}
}
打印出来的内容
姓名:阿尔弗雷德
等级:3
年龄:18
生命值:270
伤害:0
伤害修正:5
姓名:阿尔弗雷德
等级:3
年龄:18
生命值:270
伤害:0
伤害修正:5
应该打印什么
名称:Alfred
等级:3
年龄:18
HP:270
伤害:[随机]
伤害修正:[随机]
姓名:尼尔
等级:2
年龄:20
生命值:300
伤害:[随机]
伤害修正:[随机]
非常感谢您的帮助,我希望这不是一个愚蠢的问题。此外,据我所知,在这个网站上没有提出任何与此问题类似的问题。
解决方案
此处使用 static 关键字意味着“Character”类的任何对象在这些属性中必须具有相同的值。因此,当您创建一个新的 Character 对象时,之前创建的 Character 对象的所有属性都会被覆盖。摆脱所有这些静态关键字,你应该没问题。