我希望这些对象在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()我有这些对象
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());
如果要将名称分配保留在Fighter类中,请使用静态变量来保存使用过的名称列表。您需要确保您创建的战斗机没有超过名称数组。否则,它将无限期地循环。我将由您自己决定这一部分。这至少应该使您走上正确的道路。
import java.util.ArrayList; public class Fighter { private String name; private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot", "littlegirl" }; private static int id = 0; private static ArrayList<String> usedNames = new ArrayList<String>(); public void Fighters(){ id++; String checkedName = ""; do{ checkedName = names[(int) (Math.random() * names.length)]; if(!usedNames.contains(checkedName)) break; } while(true); name = checkedName; usedNames.add(name); } public String toString(){ return String.format(id+" Name:%-5s, name"); } }