【发布时间】:2015-07-29 00:59:03
【问题描述】:
- 当我编译我的程序时,我得到
error: cannot find symbol - 当我声明变量时,我在
getMove()方法中得到error: variable random is already defined in method。 - 给我这个错误的变量是我的
random变量。 - 请注意,所有如果 语句不能移动,它们必须保持在你的顺序 见他们。
- 请注意,如果
myCount == 0,我只能更改random。我想保留random,否则它是以前的值。
这是我的课程代码:
public class Frog extends AbstractCritter
{
private int myDirection;
private int myCount;
public Frog()
{
super('F');
myDirection = CENTER;
myCount = 0;
}
public int getMove(CritterInfo theInfo)
{
int result = CENTER;
if (myCount == 0)
{
double random = Math.random();
}
if (random < 0.25)
{
myDirection = NORTH;
}
else if (random < 0.5)
{
myDirection = SOUTH;
}
else if (random < 0.75)
{
myDirection = EAST;
}
else
{
myDirection = WEST;
}
myCount++;
if (myCount == 3)
{
myCount = 0;
}
if (theInfo.getNeighbor(myDirection) == 'S')
{
result = CENTER;
}
else
{
result = myDirection;
}
return result;
}
}
如果有任何不清楚的地方,请在评论中告诉我。谢谢。
【问题讨论】:
-
double random = Math.random();是在if (myCount == 0)的上下文中声明的,这使得它对方法的其余部分不可用,但是如果您在此语句之前声明另一个变量,您将获得重复的声明跨度> -
@MadProgrammer 请查看更新后的问题。我需要它在 if 语句中,因为我希望它保持该值直到
myCount为 0。在int result = CENTER;下面声明它也不起作用,它会给出错误。 -
@SotiriosDelimanolis 请参阅我对 MadProgrammer 的回复。
-
但是变量是方法的本地变量,所以当方法存在时,它的价值就丢失了!?
-
使用
random将if-else-if块移动到声明random的块中。
标签: java class compiler-errors