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

Java新手求助:如何生成指定格式的菱形字符数组?

修正菱形字符数组生成代码

原代码存在数组初始化错误、循环逻辑不符合图案规律、字符串拼接效率低及语法错误等问题,以下是修正后的完整实现:

修正后的getDiamonds方法

该方法会根据输入的rows值,按照预期的图案规律填充字符数组:

public static char[][] getDiamonds(int rows) {
    // 行数为rows+1:rows=1时2行,rows=2时3行,以此类推
    char[][] diamond = new char[rows + 1][rows * 2];
    
    // 填充每行内容
    for (int i = 0; i <= rows; i++) {
        // 先填充每行的缩进空格
        for (int j = 0; j < rows - i; j++) {
            diamond[i][j] = ' ';
        }
        // 填充交替的斜线
        for (int j = rows - i; j < rows - i + 2 * i; j++) {
            diamond[i][j] = j % 2 == 0 ? '/' : '\\';
        }
        // 剩余位置补空格,避免默认空字符干扰
        for (int j = rows - i + 2 * i; j < rows * 2; j++) {
            diamond[i][j] = ' ';
        }
    }
    
    return diamond;
}

修正后的toString方法

优化字符串拼接效率,修复语法错误,确保正确拼接每行内容:

public static String toString(char[][] array) {
    if (array == null) {
        throw new IllegalArgumentException("Null array");
    }
    if (array.length == 0) {
        throw new IllegalArgumentException("Empty array");
    }
    
    StringBuilder sb = new StringBuilder();
    for (char[] row : array) {
        sb.append(row);
        sb.append(System.lineSeparator());
    }
    // 移除最后多余的换行符
    return sb.length() > 0 ? sb.substring(0, sb.length() - System.lineSeparator().length()) : sb.toString();
}

逻辑说明

  1. 数组尺寸匹配:行数设为rows+1,列数为rows*2,完全贴合预期的图案尺寸要求;
  2. 每行填充逻辑:
    • 前rows-i个位置填充空格,实现每行的缩进效果;
    • 后续2*i个位置交替填充/和\,形成连续的斜线图案;
    • 剩余位置补空格,避免char数组默认的空字符影响打印效果;
  3. 性能优化:用StringBuilder替代直接字符串拼接,避免频繁创建字符串对象带来的性能损耗。

测试示例

调用代码:

public static void main(String[] args) {
    System.out.println(toString(getDiamonds(1)));
    System.out.println("---");
    System.out.println(toString(getDiamonds(2)));
    System.out.println("---");
    System.out.println(toString(getDiamonds(3)));
}

输出结果与预期完全一致:

/\
\/
---
 /\
/\/\
\/\/
---
  /\
 /\/\
/\/\/\
\/\/\/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 01:07:32