我希望这些对象在 main 中声明的所有对象中仅打印一次数组中的随机名称。我的问题是它会显示名称两次或更多。
public class Fighters {
private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot", "littlegirl" };
private static int id = 0;
public Fighters(){
id++;
name = names[(int) (Math.random() * names.length)];
}
public String toString(){
return String.format(id+" Name:%-5s, name);
}
}
在main()
我有这些对象
Fighters a1 = new Fighters();
System.out.println(a1.toString());
Fighters a2 = new Fighters();
System.out.println(a2.toString());
Fighters a3 = new Fighters();
System.out.println(a3.toString());