我正在处理我的第一个作业,一个类引用另一个类,恐怕我错过了一些重要的东西,当我运行测试类时,字符串变量“direction”返回 null
我试过更改访问器、方法类型并重新编写代码,但它们似乎都不起作用
public class Bug
{
private int position;
private boolean directionRight;
private String direction;
public String result;
//setting starting position for bug
public Bug()
{
position = 0;
directionRight = true;
}
//move the bug one increment
public int Move()
{
if (directionRight == true)
{
++position;
}
else
{
--position;
}
return position;
}
//change direction of bug
public Boolean Turn()
{
this.directionRight = !this.directionRight;
return directionRight;
}
//returns direction of bug in form of a string
public String Direction()
{
if (directionRight == true) {
String direction = "right";
}
else {
String direction = "left";
}
return direction;
}
//string with direction and position of the bug
public String toString()
{
String result = "the direction is: " + direction + " the position is: " + position;
return result;
}
}
---
public class Test
{
public static void main(String[] args)
{
Bug Worm = new Bug();
//direction = right, position = 3
Worm.Move() ;
Worm.Move() ;
Worm.Move() ;
Worm.Move() ;
Worm.Move() ;
Worm.Turn() ;
Worm.Move() ;
Worm.Move() ;
Worm.Move() ;
Worm.Turn() ;
Worm.Move() ;
System.out.println(Worm.toString());
}
}
我希望测试返回的方向是:正确的位置是:3
相反,我得到的方向是:null 位置是:3
米琪卡哇伊
湖上湖
相关分类