我的任务是创建一个程序,该程序将使雀科机器人在指定的时间内随机移动一些,同时计算它在移动过程中检测到的对象数量,并返回该数量然后显示出来。
我可以让机器人随机移动,也可以让它对它检测到的对象进行计数-但不能同时进行。
主要的:
int millsec = 5000;
int obstacleOccur = finchRandom(millsec);
System.out.println(obstacleOccur);
方法:
static public int finchRandom(int x)
{
Finch myf = new Finch();
Random rand = new Random();
int obs = 0;
long time = System.currentTimeMillis()+x;
while(time - System.currentTimeMillis() > 0)
{
if (myf.isObstacle())
{
obs++; //this counts the obstacles
System.out.println("Obstacle");
} //below activates the wheels to move randomly,
//the function is setWheelVelocities(leftWheel,rightWheel,duration)
myf.setWheelVelocities(rand.nextInt(150)-75,rand.nextInt(150)-75,rand.nextInt(x/2));
}
return obs; //returns the count of obstacles
}
我相信这是因为在雀科机器人四处移动时,无法运行if语句和用于计数障碍物的增量。有什么办法解决吗?
提前致谢。
答案是多线程编程,您的工作是弄清楚如何使用THread或Runnable或lambda表达式来执行此操作。因为任何给定的线程一次只能做一件事,并且您一次至少需要做两件事。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句