I'm trying to add multiple values to an ArrayList via an if/else statement. The variable numberOfShips declares how many as a field. However, when I print out .size(), the size is only 1, with the latest added object being the one in there. I can't figure out what I'm doing wrong. I know ArrayList increases implicitly in size as elements are added, so that can't be it.
public ArrayList<Ship> createFleet(int choice) {
ArrayList<Ship> fleet = new ArrayList<Ship>();
if (count < numberOfShips && choice > 0 && choice < 5) {
if (choice == 1) {
Ship ac = new Ship("Aircraft carrier", 5, false);
fleet.add(ac);
count++;
System.out.println("Aircraft carrier has been added to fleet.");
} else if (choice == 2) {
Ship bs = new Ship("Battleship", 4, false);
fleet.add(bs);
count++;
System.out.println("Battleship has been added to fleet.");
} else if (choice == 3) {
Ship sm = new Ship("Submarine", 3, false);
fleet.add(sm);
count++;
System.out.println("Submarine has been added to fleet.");
} else if (choice == 4) {
Ship ds = new Ship("Destroyer", 3, false);
fleet.add(ds);
count++;
System.out.println("Destroyer has been added to fleet.");
} else if (choice == 5) {
Ship sp = new Ship("Patrol Boat", 2, false);
fleet.add(sp);
count++;
System.out.println("Patrol boat has been added to fleet.");
}
} else {
System.out.println("Not an option.");
}
return fleet;
}
switchstatement? it might help you here.newlist in your method.