You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java绘制星号矩形时如何避免方法返回null值?

问题根因

你修改draw()返回值为void不生效的核心原因是:Java的toString()方法默认返回类型固定为String,你的原有代码中toString()直接返回draw()的执行结果,因此只要toString()还在调用draw(),draw()就必须返回String类型,修改为void会直接触发编译错误。
同时你运行结果最后多出来的null,就是draw()返回的null值被System.out.println打印出来导致的。

最优解决方案

调整draw()方法的逻辑:不要在方法内部直接执行打印操作,改为把矩形的星号内容拼接为完整字符串返回,既可以满足toString()的返回要求,也完全不需要再返回无用的null值。
另外注意你现有的Rectangle类缺少测试代码中用到的双参数构造方法,需要补上否则运行会报错。

修改后的完整代码如下:

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

    // 新增测试代码需要的双参数构造方法
    public Rectangle(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public String draw() {
        // 用StringBuilder拼接矩形内容
        StringBuilder sb = new StringBuilder();
        for(int i = 1; i <= this.height; i++){
            for(int j = 1; j <= this.width; j++){
                sb.append("* ");
            }
            sb.append("\n");   
        }      
        // 直接返回拼接好的字符串,无需返回null
        return sb.toString();
    }

    public String toString() {
        return draw();
    }
}

测试代码不需要修改,运行后会直接输出3行5列的星号矩形,不会再出现末尾的null。

内容的提问来源于stack exchange,提问作者Kay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 17:36:07