I'm working on an assignment and it's going fairly well, but I am confused about one thing so far. The point is to learn about inheritance and reading through existing code. Without adding another method, I need to make the getMove() method return the same random number three times in a row, and then pick a new random number and have it return the new number three times. etc. etc.
There are several other classes, including a class that maintains a count separate from the one I established here. If it would be useful to see any of those classes let me know and I'll post them, but I think they are fairly irrelevant to the question.
Edit: Clarification
I need to make the getMove() method return one int per call. The 1st 3 calls should return the same randomInt. After that a new randomInt should be chosen, and that should be returned for the next three calls. This should repeat as long as it's called.
The final solution:
public class Crab extends SeaCreature {
private static final char CRAB = 'C';
private int direction = rand.nextInt(4);
private int count;
/**
* Construct a SeaCreature object with the given character representation
* @param c the character for this SeaCreature
*/
public Crab(){
su开发者_运维问答per(CRAB);
}
/** Answers back the next move for this SeaCreature.
* @return 0, 1, 2, or 3
*/
public int getMove() {
if (count < 3) {
count ++;
return direction;
}
count = 1;
direction = rand.nextInt(4);
return direction;
}
}
Not that it's a "problem", but your fields should be instance fields (ie not static).
However, to isolate the problem from your classes, here's code that works. Note that you can get the same move on subsequent calls to rand().
private static int direction = rand();
private static int count;
public static int getMove()
{
if (count < 3)
{
count++;
return direction;
}
count = 0;
direction = rand();
return direction;
}
private static int rand()
{
return (int) (Math.random() * 4); // 0, 1, 2 or 3
}
I can see the problem I think.
Hint - you need to think through carefully which state belongs to all Crabs, and which state is specific to an individual Crab. You've currently got that wrong, and all Crabs are sharing some state that they shouldn't. Assuming that there are lots of live Crab instances, this will result in getMove()
not behaving as you want it to.
精彩评论