This site requires JavaScript, please enable it in your browser!
Greenfoot back
zyxelementxyz
zyxelementxyz wrote ...

2014/11/14

java.util.list problem

zyxelementxyz zyxelementxyz

2014/11/14

#
I am trying to get a Object to move in a random direction when touching Rock.class but when I look on the Greenfoot API for the methods that go with java.util.list there is limited methods that would correlate with the function if touching. I know this may be easy for some but I am very new to this. I have if(size(0)) { true }. but there is a compiling error. Once again. I need the Wombat to move in a random direction when touching Rock.class but the code is setup in Java.util.list. Any help is apprectiated. Thank you so much.
danpost danpost

2014/11/14

#
First, the 'size' method of the List class does not take any parameters (the round brackets should remain empty when 'size' is called). Second, you cannot just call 'size' -- it needs a List object to be called on (the List object you want the size of). If you had a List object in a variable called 'list', then you could write 'int listSize = list.size();'. Finally, in your example, 'if(size(0)) { true }', if you wanted to know if a list was empty (which would have a size of zero), then you can use the List object method 'isEmpty()', which returns a boolean (true/false) value. Now, there are, as you say, a few methods in the Actor class that return List objects -- these include 'getIntersectingObjects', 'getNeighbours', 'getObjectsInRange', to name most of them. The 'isTouching' method basically uses the 'getIntersectingObjects' method to get a List object, executes the 'isEmpty()' method on the list and returns to the calling statement the opposite value of what it ended up with. In code:
1
2
3
4
5
if (isTouching(Rock.class))
// is synonymous with
if ( ! getIntersectingObjects(Rock.class).isEmpty() )
// as well as (though, one of the above should be used when possible)
if (getIntersectingObjects(Rock.class).size() > 0)
The above code lines return a true value when the acquired list is NOT empty. If you need to know when the list acquired is empty, just negate the conditions by adding or removing the ' ! ' ('logical compliment' or 'boolean inversion') operator in the first two examples or compare for equality (use '==') in the third. BTW, the proper syntax for an 'if' statement is as follows: if ( boolean-expression ) { // code to execute if true } else { // code to execute if false } the 'else', with its following block of code, is optional.
You need to login to post a reply.