我正在使用地图来存储有关军队的信息,然后将地图作为参数传递给函数以创建军队。输入如下:
Humans : {30,40}
Elfs: {20,40,60}
Humans: {10}
我用来存储信息的方法效果不佳,因为当我添加具有另一个值的键时,它正在创建一个新对象,因为我正在使用该类的新实例。谁能帮我解决这个问题?
public class InputInformation {
public static Map<CreatureFactory, ArrayList<Integer>> description;
public InputInformation(){
description = new HashMap<CreatureFactory,ArrayList<Integer>>();
}
public static Map<CreatureFactory, ArrayList<Integer>> createArmy(BufferedReader buffer)
throws IOException,NumberFormatException {
String option;
CreatureFactory factory;
ArrayList<Integer> warriors;
Map<CreatureFactory, ArrayList<Integer>> description = new HashMap<CreatureFactory, ArrayList<Integer>>();
while(true){
createArmysMenu();
while((option = buffer.readLine()) != null){
switch(option){
case "H":
factory = new HumansFactory();
warriors = getTroopNumberOfWarriors(buffer);
description.put(factory, warriors);
break;
case "E":
factory = new ElfsFactory();
warriors = getTroopNumberOfWarriors(buffer);
description.put(factory, warriors);
break;
case "D":
factory = new DwarfsFactory();
warriors = getTroopNumberOfWarriors(buffer);
description.put(factory, warriors);
break;
case "O":
factory = new OrcsFactory();
warriors = getTroopNumberOfWarriors(buffer);
description.put(factory, warriors);
break;
case "W":
factory = new WargsFactory();
warriors = getTroopNumberOfWarriors(buffer);
description.put(factory, warriors);
break;
case "F":
System.out.println("Your army has been created");
showPrincipalMenu();
return description;
default:
System.out.println("Mistmatch");
break;
}
}
}
}
private static ArrayList<Integer> getTroopNumberOfWarriors( BufferedReader buffer)
throws NumberFormatException, IOException {
Integer numberOfWarriors;
ArrayList<Integer> warriors = null;
while(true){
enterNumberOfWarriors();
numberOfWarriors = Integer.parseInt(buffer.readLine());
if(numberOfWarriors == -1){
createArmysMenu();
break;
} else {
if(warriors == null){
warriors = new ArrayList<Integer>();
warriors.add(numberOfWarriors);
} else {
warriors.add(numberOfWarriors);
}
}
}
return warriors;
}
public static void showPrincipalMenu(){
System.out.println("To create the free army press 1");
System.out.println("To create the dark army press 2");
System.out.println("To start the fight, press 0");
}
public static void createArmysMenu(){
System.out.println("To add a Humans troop, press H");
System.out.println("To add an Elfs troop, press E");
System.out.println("To add an Dwarfs troop, press D");
System.out.println("To add an Orcs troop, press O");
System.out.println("To add an Wargs troop, press W");
System.out.println("When you've done adding the troops, press F");
}
public static void enterNumberOfWarriors(){
System.out.println("Enter the number of warriors for this troop");
System.out.println("To add a new troop press -1");
}