如何修复 toString 中意外的字符串输出 'null'

How to I fix a unexpected string output 'null' in toString

我正在做我的第一个作业,一个 class 引用另一个 class,恐怕我错过了一些重要的东西,当我 运行 测试 class, 字符串变量 'direction' returns null

我试过更改访问器、方法类型并修改代码,但 none 似乎有效

</p> <pre><code>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()); } }

我希望测试能够 return 方向为:右 位置为:3

相反,我得到 方向是:null 位置是:3

您永远不会调用 Direction() 方法,该方法将非空值分配给 direction。但是您必须删除 String direction = 并将其替换为 this.direction =。这样,您引用的是成员变量,而不是您创建的本地化字符串。

您没有调用或设置 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;
}