嵌套if和何时添加到arraylist不按预期工作

时间:2014-10-12 20:54:26

标签: java if-statement while-loop

我在此方法中遇到if和while语句的问题。所需的功能是选择1到5之间的数字,并将对象添加到arraylist。类中有一个名为numberOfShips的字段,用于while循环,它决定了数组中的最大对象数。 count变量应该跟踪达到限制的时间。

然而,事实并非如此。我选择例如1,它增加了1个numberOfShips次数。然后它说船队已满,因为这是极限。我似乎无法弄清楚问题是什么,因为我已经尝试了if语句的几个变体,并且我也试过了do while,但是没有用。

public ArrayList<Ship> createFleet(int choice) {
        ArrayList<Ship> fleet = new ArrayList<Ship>();
        int count = 0;
        if(choice > 1 && choice < 5) {
            while ((count < numberOfShips)) {
                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 {
                    Ship sp = new Ship("Patrol Boat", 2, false);
                    fleet.add(sp);
                    count++;
                    System.out.println("Patrol boat has been added to fleet.");
                }
            } //while
        } else {
            System.out.println("Not an option.");
        }
        System.out.println("Fleet contains maximum ships.\nYour fleet is:");
        for (int i = 0; i < fleet.size(); i++) {
            System.out.println(fleet.get(i));
        }
        start();
        return fleet;
    }

1 个答案:

答案 0 :(得分:0)

你不需要时间,你需要做以下

if(count < numberOfShips && choice > 0 && choice < 5) {
   // Check which ship
}

此外,变量count应该在方法之外,因此:

public class Test { 
   private int numberOfShips = 400;
   private int count;

   public ArrayList<Ship> createFleet(int choice) {
       ArrayList<Ship> fleet = new ArrayList<Shipe>();
       if(count < numberOfShips) {
         if(choice > 0 && choice < 5) {
            //appropriate ship..
         }
       } else {
          System.out.prinln("Capactity reached");
       }  
   }
}

代码中的while将继续,直到重新调整容量,而不是。 虽然是一个循环,但是检查是用简单的单词