有没有办法避免“null”返回?

0 java return-value

我正在研究一种使用星号绘制矩形的方法。我的方法确实返回了所需的矩形,但它迫使我添加一个带有“null”值的返回语句。我怎样才能摆脱这个“空”值?在方法中使用“void”而不是“String”不起作用。

我的代码如下:

public class Rectangle {
   
    int width;
    int height;
    
    public Rectangle() {
        this.width = 0;
        this.height = 0; 
    }

    public String draw() {
        for(int i = 1; i <= this.height; i++){
            for(int j = 1; j <= this.width; j++){
                System.out.print("* ");
            }
            System.out.print("\n");   
        }      
        return null;
    }

    public String toString() {
        return draw();
    }
}
Run Code Online (Sandbox Code Playgroud)

通过运行此代码:

public class Essay {
    public static void main(String[]args) {
        Rectangle rectangle = new Rectangle(5, 3);

        System.out.println(rectangle.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

结果是:

在此输入图像描述

小智 7

toString实现应该返回表示对象的字符串值,而不是直接打印它,因为不能保证方法的调用者会想要打印它。例如,想象一下,您想将 的结果写入toString文件 - 如果它只是打印到控制台并且没有返回任何内容,您会怎么做?

解决此问题的最佳方法是修改您的实现,toString将星号矩形构建为字符串并返回它而不打印任何内容。但如果你只是想解决这个问题,你可以返回一个空字符串而不是 null。