2014-10-12 1 views
0

이 메서드에서 if 및 while 문에 문제가 있습니다. 원하는 기능은 1에서 5 사이의 숫자를 선택하고 객체를 arraylist에 추가하는 것입니다. 클래스에는 while 루프에 사용되는 numberOfShips라는 필드가 있습니다.이 필드는 배열에있는 객체의 최대 개수를 결정합니다. count 변수는 한계에 도달 한 시점을 추적해야합니다.중첩 된 arraylist에 추가 할 때 중첩되지 않는다.

그러나 그런 일은 발생하지 않습니다. 예를 들어 1, 선택 1 numberOfShips 시간을 추가합니다. 그때 그것은 함대가 꽉 찼다 고 말합니다, 왜냐하면 그것이 한계이기 때문입니다. if 문과 함께 여러 가지 변형을 시도했기 때문에 문제가 무엇인지 파악할 수없는 것 같습니다. 그리고 do는 작동하지 않는 do를 시도했습니다.

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; 
    } 

답변

0

당신이 잠시 필요 없어요, 당신은 또한

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

다음을 수행해야 할 변수 수는 따라서,이 방법 밖에 있어야한다 :

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"); 
     } 
    } 
} 

그동안을에 코드는 capactiy가 reched 때까지 계속되며, 그렇지 않습니다. 루프가있는 동안 간단한 단어로 넣는 수표 인 경우

관련 문제