我正在完成任务并且进展相当顺利,但到目前为止我对一件事感到困惑。关键是要学习继承和阅读现有代码。在不添加其他方法的情况下,我需要让getMove()方法连续三次返回相同的随机数,然后选择一个新的随机数并让它返回三次新数字。等等。
还有其他几个类,包括一个与我在此建立的计数分开的计数的类。如果看到任何这些课程让我知道并且我会发布它们会很有用,但我认为它们与这个问题无关。
编辑:澄清
我需要让getMove()方法每次调用返回一个int。前3个调用应该返回相同的randomInt。之后应该选择一个新的randomInt,并且应该为接下来的三次调用返回。只要它被调用就应该重复。
最终解决方案:
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;
}
}
答案 0 :(得分:3)
不是说它是一个“问题”,但你的字段应该是实例字段(即不是静态字段)。
但是,要将问题与您的类隔离开来,这里的代码可行。请注意,您可以在后续调用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
}
答案 1 :(得分:3)
我可以看到我认为的问题。
提示 - 你需要仔细思考哪个州属于所有螃蟹,哪个州特定于个体螃蟹。你现在错了,所有螃蟹都分享了一些不应该的状态。假设有很多实时Crab实例,这将导致getMove()
无法按照您的意愿行事。