我正在处理我的第一个作业,一个类引用另一个类,恐怕我错过了一些重要的东西,当我运行测试类时,字符串变量“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
2 回答
米琪卡哇伊
TA贡献1998条经验 获得超6个赞
您不是在调用或设置direction. 这应该解决它。
public String Direction()
{
if (directionRight == true) {
direction = "right";
}
else {
direction = "left";
}
return direction;
}
public String toString()
{
String result = "the direction is: " + Direction() + " the position is: " + position;
return result;
}
湖上湖
TA贡献2003条经验 获得超2个赞
您永远不会调用Direction()
将非空值分配给的方法direction
。但是您必须将String direction =
其删除并替换为this.direction =
. 这样,您引用的是成员变量,而不是您创建的本地化字符串。
添加回答
举报
0/150
提交
取消