我正在为我的 AP Comp Sci 类(class)编写一个基本的 RPG。对于这个问题,唯一重要的两个类是角色和客户端。客户端运行一切,角色拥有许多角色传统上拥有的属性。
问题:我正在创建名为“Character”的类的 2 个不同实例。但是,当我尝试使用 toString() 方法打印它们时,仅打印最近实例化的一个。
尝试的解决方案我尝试在其他类中编写 toString() 方法,并使用 Character 作为参数,我用 google 搜索了这个问题,但没有找到类似的内容。还尝试添加“这个”。在 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;
}
}
打印内容
姓名:阿尔弗雷德
类(class):3
年龄:18岁
生命值:270
伤害:0
伤害调整值:5
姓名:阿尔弗雷德
类(class):3
年龄:18岁
生命值:270
伤害:0
伤害调整值:5
应该打印什么
姓名:阿尔弗雷德
类(class):3
年龄:18岁
生命值:270
伤害:[随机]
伤害修正:[随机]
姓名:尼尔
类(class):2
年龄:20岁
生命值:300
伤害:[随机]
伤害修正:[随机]
非常感谢您的帮助,我希望这不是一个愚蠢的问题。另外,据我所知,该网站上没有提出任何与此问题类似的问题。
最佳答案
这里使用 static 关键字意味着“Character”类的任何对象都必须在这些属性中具有相同的值。因此,当您创建新的角色对象时,先前创建的角色对象的所有属性都会被覆盖。摆脱所有这些静态关键字,你应该没问题。
关于java - 为什么这些Character对象不保留特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60214045/