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

如何在toString方法中为不同Row-Col块添加分隔空行?

解决toString方法中Row-Col块间的换行问题

我正在完成一个分为三部分的实验,需要实现toString()方法,调用后预期返回格式如下:

Row 0 Col 0 
30.5 grams of ice 
42.3 grams of sulfur 
0.6 grams of silver 
 
Row 3 Col 5 
21.0 grams of water 
 
Row 3 Col 7 
45.2 grams of water 
31.2 grams of elixir 

我的问题不是无法获取toString()方法的信息,而是不知道如何在两个Row-Col块之间添加额外换行符(比如在“0.6 grams of silver”与“Row 3 Col 5”之间)。当前我的toString()方法实现如下:

public String toString() {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            Vial vial = rack[i][j];
            if (vial != null) {
                result.append("Row " + i + " Col " + j + "\n");
                result.append(vial.toString());
            }
        }
    }
    return result.toString();
}

运行测试时得到不符合预期的结果:

Row 0 Col 0
45.2 grams of sulfur
10.1 grams of lead
30.0 grams of ice
4.6 grams of elixirRow 1 Col 5
30.0 grams of ice

正确格式应为:

Row 0 Col 0
45.2 grams of sulfur
10.1 grams of lead
30.0 grams of ice
4.6 grams of elixir

Row 1 Col 5
30.0 grams of ice

我觉得可以用if语句解决,但不确定判断条件,而且这个语句应该放在result.append(vial.toString());之后。


解决方案

核心思路是区分第一个非空Row-Col块和后续块,在后续块前添加空行,或者先收集所有块内容再统一用空行拼接,两种方式都能解决问题:

方法一:用标记变量控制换行

public String toString() {
    StringBuilder result = new StringBuilder();
    boolean firstBlock = true;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            Vial vial = rack[i][j];
            if (vial != null) {
                if (!firstBlock) {
                    // 非第一个块,先添加两个换行形成空行
                    result.append("\n\n");
                } else {
                    firstBlock = false;
                }
                result.append("Row " + i + " Col " + j + "\n");
                result.append(vial.toString());
            }
        }
    }
    return result.toString();
}

注意:确保vial.toString()的结尾包含换行符,否则需要在result.append(vial.toString());后额外添加\n,避免出现物质行与下一个Row标题连在一起的情况。

方法二:收集块内容后统一拼接

这种方式更简洁,还能避免末尾多出空行:

import java.util.ArrayList;
import java.util.List;

public String toString() {
    List<String> blocks = new ArrayList<>();
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            Vial vial = rack[i][j];
            if (vial != null) {
                StringBuilder block = new StringBuilder();
                block.append("Row " + i + " Col " + j + "\n");
                block.append(vial.toString());
                blocks.add(block.toString());
            }
        }
    }
    // 用两个换行符连接所有块,仅在块之间添加分隔符
    return String.join("\n\n", blocks);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 02:15:26