[英]Creating bug class, which moves back to original position
I'm very new to Java and I'm confused on how to create a method that goes back to original position, going through each step and turn. 我是Java的新手,我对如何创建返回到原始位置的方法,每个步骤和每个步骤都感到困惑。
This is an assignment for school and essentially, I have to create a Bug class, which moves 1 unit of distance on a horizontal line, turns, reverses, and moves back to original position. 这是学校的一项工作,从本质上讲,我必须创建一个Bug类,该类在一条水平线上移动1单位距离,然后转弯,反转并移回原始位置。
Here's the code I have so far: 这是我到目前为止的代码:
public class Bug
{
private int position;
private String direction;
public void initialPosition(int position ) {
position=0;
}
public void initialDirection(String direction) {
direction="right";
}
public void setPosition (int position) {
this.position = position;
}
public int getPosition() {
return position;
}
public void setDirection (String direction) {
this.direction = direction;
}
public String getDirection() {
return direction;
}
public void move() {
position+=1;
}
public void reverseDirection() {
if (direction=="right") {
direction="left";
}
else {
direction="right";
}
}
public String toString() {
return "Position: " + position + " & Direction: " + direction;
}
}
Any tips on code will be super appreciated as well. 任何有关代码的技巧也将受到高度赞赏。 Thanks!
谢谢!
In your move() function, get the current direction and then use an if statement so that 在您的move()函数中,获取当前方向,然后使用if语句,以便
if (direction.equals("right")) {
position+=1;
}
else {
position-=1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.