okay so heres the deal. I have an object created to resemble a room in which i've created an array to store Animal objects within. Now in this program there will be several rooms and the Animal objects must be able to move between these rooms when a certain condition arises. What sort of algorithm should i be thinking about implementing into this?
To be clear I want the Animal objects to be able to remove themselves from the Array stored within their current Room object and be able to append themselves to another existing array in another existing Room object.any ideas?
3 Replies - 171 Views - Last Post: 08 February 2012 - 12:37 PM
Topic Sponsor:
#1
Moving an Object strored in an Array to another Array.
Posted 08 February 2012 - 07:51 AM
Replies To: Moving an Object strored in an Array to another Array.
#2
Re: Moving an Object strored in an Array to another Array.
Posted 08 February 2012 - 08:29 AM
There is no "algorithm" for this problem, it is all dependent on how you write your code. You stated the requirments for a animal to move from room to room. It leaves the array of the first room and enters the array of the next. So we need to define a move() for your Room object.
public void moveTo( Animal a, Room r ){
//find a in this.animalArray
//remove a from this.animalArray
//add to r.animalArray
}
#3
Re: Moving an Object strored in an Array to another Array.
Posted 08 February 2012 - 12:28 PM
good stuff but i guess my next question is finding Animal a within the array. how can i write something that automatically finds what index the Animal is in within the array?
#4
Re: Moving an Object strored in an Array to another Array.
Posted 08 February 2012 - 12:37 PM
That varies by implementation. The most basic approach would be to loop through array and check each index until you find the one you wanted. However, think about what happens when you remove the object
if you have a basic array like this Animal[] animals, that will most likely mean you will be setting that index to null, which could cause problems unless you know how to handle it. If your allowed to use ArrayList, you will find other tools to help you search the array, and handle adding and removing much easier
if you have a basic array like this Animal[] animals, that will most likely mean you will be setting that index to null, which could cause problems unless you know how to handle it. If your allowed to use ArrayList, you will find other tools to help you search the array, and handle adding and removing much easier
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|