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(){
super(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().