2013-12-06 4 views
0
public abstract class Bee { 
    static Hive hive = Garden.hive; 
    protected int type; 
    protected int age; 
    protected int health = 3; 

    protected int getType() 
    { 
     return type; 
    } 
    protected int getAge() 
    { 
     return age; 
    } 
    protected int getHealth() 
    { 
     return health; 
    } 

    protected void setAge(int age) 
    { 
     this.age = age; 
    } 
    protected void setType(int input) 
    { 
     this.type = input; 
    } 
    protected abstract boolean eat(); 
    protected abstract void anotherDay(); //the bees tasks for day (should include eat()) 

} 


    public class Queen extends Bee { 

    protected Queen() 
    { 
     setType(1); 
    } 
    protected int eggTimer = 0; // tracks when to add a new egg (not using age incase an external factor causes layEgg) 

    // removed code to avoid being too long 

    protected void layEgg() { 
     Egg egg = new Egg(); 
     hive.addBee(egg); //fix?? 
     eggTimer = 0; 
    } 
} 



     import java.util.ArrayList; 

    class Hive { 


     ArrayList<Bee> beeList = new ArrayList<Bee>(); 
     // code removed 
     public int beeIndex; // used to know what the index of bee you are in is 


     protected void addBee(Bee bee) { //Its running this and getting into the beelist.add(bee) but after there is nothing new in beeList. 
      if (beeList.size() < 100) { 
       beeList.add(bee); 
      } else { 
       System.out.println("Too many Bees to add more"); 
      } 
     } 

     // removed code to avoid being too long 

     protected void anotherDay() { 
      int i = 0; 
      for (Bee bee : beeList) { 
       i++; 
       bee.anotherDay(); 
       beeIndex = i; 
      } 
     } 
    } 

код работает без ошибок, но когда дело доходит до метода layEgg его Мента добавить яйцо (еще один класс, который расширяет пчелу) в ArrayList в улье. Он запускается и метод addBee и перебирает beeList.add, но он не добавляет объект еще. Любые советы будут очень признательны.Добавление новых объектов ArrayList разве работает

Я вырезал часть кода, чтобы сделать пост короче layEgg запущен, когда anotherDay() называется 3-й раз в Queen.

public class Garden { 
    static Hive hive = new Hive(); 
    protected int flowerIndex; 
    ArrayList<Flower> flowerList = new ArrayList<Flower>(); 

    protected void anotherDay() { 
     int i = 0; 
     for (Flower flower : flowerList) { 
      i++; 
      flower.anotherDay(); 
      flowerIndex = i; 
     } 
    } 

    protected void addHive(Hive hiveInput) { 
     Hive hive = hiveInput; 
    } 

    protected void addFlower(Flower flowerInput) { 
     Flower flower = flowerInput; 
    } 

    protected Flower getFlower(int input) { 
     return flowerList.get(input); 
    } 

    protected Flower findFlower() // finds the size of the arrayList and then 
            // creates a random number within the array 
            // to use as an index 
    { 

     int listSize = flowerList.size(); 
     Random random = new Random(); 
     int index = random.nextInt(listSize); 
     return flowerList.get(index); 
    } 

    protected int getFlowerListSize() 
    { 
     return flowerList.size(); 
    } 

} 
+0

Скорее всего, это добавление пчелы, но ваш тест не работает. Можете ли вы привести пример того, что вы делаете и что не удается? –

+0

Откуда вы его не добавили? вы используете тот же объект Hive для печати пчелы? –

+0

Что такое 'Сад'? –

ответ

0

Вещи для проверки (с использованием контрольных точек, или отладочных инструкций, или и того и другого).

  • ли все указывает на тот же улей объект
  • ли все указывает на тот же объект List

Я могу гарантировать, что добавление материала в списки в Java работает - так что ваш код является:

  • Не добавлять материал
  • добавление вещи к неправильному списку
  • Извлечение из списка после добавления

Просто проверьте все эти случаи и узкие вещи, пока не найдете причину.

+0

Кажется, что его добавили к другой Королеве в id21, а яйцо в id40 кажется странным, поскольку я не думал, что создаю более 1 beeList как когда Hive создается как статический – user1642671

+0

Означает ли это, что проблема в Bee со статическим улей улья = Garden.hive; или является дополнительным атрибутом arrayList, который будет в другом месте? – user1642671

+0

Одно из первых правил отладки - проверьте ваши предположения :) Я не знаю, в чём проблема, так как это ваш код, и я не вижу этого достаточно. (И у вас нет времени на отладку кода бесплатно;)). Все, что я могу сказать, это то, что вы создаете или что-то ошибаетесь. Попробуйте протоколировать каждый раз, когда список может быть создан и посмотреть, что происходит. Вы можете сделать новый Exception(). PrintStackTrace(), чтобы получить трассировку стека для любой точки кода, например. –

Смежные вопросы