我一直在使用机器人学习套装进行单一任务,我遇到了麻烦。我已经创建了一个名为DeliveryBot的类,为了使其工作,int'size'需要在其他方法中使用。
import becker.robots.*;
public class DistributeBot extends RobotSE
{
//constructor
public DistributeBot(City aCity, int aStreet, int anAvenue, Direction aDirection, int numThings)
{
super(aCity, aStreet, anAvenue, aDirection, numThings);
}
//Methods must include one called putThings which has a parameter to define the size of the squares.
public void putThings(int size)
{
this.setSquare();
this.positionRobot();
this.setSquare();
}
private void setSquare()
{
for(int numRows = 0; numRows <= size; numRows++)
{
this.setRow();
}
}
private void setRow()
{
for(int numColumns = 0; numColumns <= size; numColumns++)
{
this.putThing();
this.move();
}
this.faceSouth();
this.move();
}
private void turnToFaceNextRow()
{
if(size & 1) == 0)
{
this.turnRight();
}
else
{
this.turnLeft();
}
}
private void faceSouth()
{
while(this.getDirection() != Direction.SOUTH)
{
this.turnRight();
}
}
private void positionRobot()
{
if(this.getDirection() == Direction.WEST)
{
this.move(size);
this.move();
this.turnLeft();
this.move();
this.turnLeft();
}
else
{
this.turnAround();
this.move();
this.turnLeft();
this.move();
this.turnLeft();
}
}
}
问题是在putThings(int size)方法中使用的int'size'的其他用法出现了“遗漏符号”错误,告诉我其他方法中所说的'size'如:
private void setSquare()
{
for(int numRows = 0; numRows <= size; numRows++)
{
this.setRow();
}
}
未被识别为相同的“尺寸”。这个想法是整个任务可以用一行代码来执行:
karel.putThings(4);
用4,即。 int size,定义'square'的尺寸。 任何帮助将不胜感激,并提前感谢。
答案 0 :(得分:1)
在不知道赋值规范的情况下很难说,但在我看来,你真的希望putThings()
功能成为构造函数的一部分。
您需要做的是在整个类的最开始(构造函数之前)声明private int size;
。你声明它没有任何值只是为了让编译器知道这个对象(DistributeBot)将有一个名为size
的属性private int
。
您可以将自己的属性声明为public
,default
,private
或protected
。在大多数情况下,您应该将属性设置为private,这样您就不会在创建对象的类之外不小心修改它们。默认只是int size;
为了修改私有变量,您可以创建通常名为getVariable()和setVariable(type var)的getter和setter,其中getVariable返回所检索变量的任何类型的变量,setVariable是设置变量的void函数。这个隐私'封装'了一个类中的属性(或者你已经完成的方法),这样就像我之前提到的那样,没有人可以从创建对象的类之外调用它们。
因此,在构造函数和类的开头之间,您将放置private int size;
,然后在构造函数中,您应该更改参数以添加(int size)。
public class DistributeBot extends RobotSE
{
private int size;
//note that although you can't see it unless you scroll to the right
//the constructor now has 'int size' as the last parameter
public DistributeBot(City aCity, int aStreet, int anAvenue, Direction aDirection, int numThings, int size)
{
super(aCity, aStreet, anAvenue, aDirection, numThings);
//you technically DON'T have to do this next line if you
//don't create the attribute 'size' for this class but you
//probably should. It's hard to tell from your description.
this.setSize(size);
//notice how below I use 'this.size' because this
//object officially has an attribute called size
this.putThings(this.size);
...
//anything else you want to do in the constructor
//you can put the functionality of putThings in here if you want
}
...
private int getSize()
{
return this.size;
}
private void setSize(int size)
{
this.size = size;
}
}