I am having problems with ArrayList items in a method that must be static. The code picks two random mice in the mice ArrayList. It then is suppose to compare the two mice to see if they are of different sex and both over the age of 1.
Here is my code
The code as is generates an error message like this for all my metods in the if loop ...
non-static method getAge(java.util.ArrayList,int) cannot be referenced from a static context
&& ((getAge(mice, a) >1) && (getAge(mice, b) >1)))
I have tried to change the code (and the methods) to not accept parameters, to something similar to this ...
but, I then get this error message:
cannot find symbol
symbol : method mice(int)
location: class Mouse ... I have imported the Java.util.ArrayList class into the Mouse class. The mice is the ArrayList and the (int) should be the index of the item in the list.
Dreadful. Never write == true. You just leave that bit out. Never write == false. You use the ! (bang operator) to negate the Boolean value.
NotbutOr better, if you simply want two mice of different sex, try
Joined: Aug 19, 2010
Thank you Narayan and Ritchie,
I've got the code in better form and compiling thanks to both of your comments.
However, the program isn't returning the results it should be. So, I'll keep at it.
I've got a few remarks about your code that hopefully will improve your code:
If your ArrayList only contains mouses or subclasses of mouse then you can declare your ArrayList to be generic:
ArrayList<Mouse> mice = new ArrayList<Mouse>();
Or even better, program against an interface instead of an implementation:
List<Mouse> mice = new ArrayList<Mouse>();
The generic part will provide compile time type safety and will remove casts from your code.
The interface part will allow you to change the list implementation without massively changing your code
and then there is no need to know the implementation details because you only need the specification on the interface.
And finally the method isMale() sounds like a prime candidate to be a property of mice.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Joined: Aug 19, 2010
Thanks everyone! I've got it working!
Joined: Oct 13, 2005
You're welcome . As an alternative to the != operator, you could try the XOR operator (caret = ^).