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

如何实现无空格输入填充char类型二维矩阵?

实现无空格(支持换行)输入填充二维矩阵

问题分析

你当前的代码使用scanner.next()读取输入,该方法会以空白字符(空格、换行、制表符等)作为分隔符,因此必须依赖空格分割矩阵元素,无法支持无空格的连续输入场景。

解决方案

下面提供两种可行的实现方式,均支持无空格输入(允许换行),并能正确填充3×3矩阵:

方法1:读取全部输入后统一处理

一次性读取所有输入内容,过滤掉所有空白字符后,按顺序逐个填充矩阵:

char[][] rand = new char[3][3];
Scanner scanner = new Scanner(System.in);

// 读取输入结束前的所有内容,过滤掉所有空白字符(换行、空格等)
String input = scanner.useDelimiter("\\Z").next().replaceAll("\\s", "");

// 校验输入字符数量是否符合要求
if (input.length() < 9) {
    System.err.println("错误:输入字符数量不足9个");
    return;
}

// 逐字符填充矩阵
int charIndex = 0;
for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
        rand[i][j] = input.charAt(charIndex++);
    }
}

// 按要求格式输出矩阵
System.out.print("[");
for (int i = 0; i < 3; i++) {
    System.out.print("[");
    for (int j = 0; j < 3; j++) {
        System.out.print(rand[i][j]);
        if (j < 2) System.out.print(",");
    }
    System.out.print("]");
    if (i < 2) System.out.print(",");
}
System.out.println("]");

方法2:逐行读取并填充

如果用户习惯按行输入(每行3个无空格字符),可以用这种方式逐行处理:

char[][] rand = new char[3][3];
Scanner scanner = new Scanner(System.in);

for (int i = 0; i < 3; i++) {
    // 读取一行输入,过滤掉该行内的空白字符
    String line = scanner.nextLine().replaceAll("\\s", "");
    
    // 校验当前行的有效字符数量
    if (line.length() < 3) {
        System.err.println("错误:第" + (i+1) + "行输入字符不足3个");
        return;
    }
    
    // 从当前行取对应位置的字符填充矩阵
    for (int j = 0; j < 3; j++) {
        rand[i][j] = line.charAt(j);
    }
}

// 按要求格式输出矩阵
System.out.print("[");
for (int i = 0; i < 3; i++) {
    System.out.print("[");
    for (int j = 0; j < 3; j++) {
        System.out.print(rand[i][j]);
        if (j < 2) System.out.print(",");
    }
    System.out.print("]");
    if (i < 2) System.out.print(",");
}
System.out.println("]");

说明

  • 两种方法都支持用户输入带换行的无空格内容(比如231\n456\n789),也支持完全连续的输入(比如231456789)。
  • 加入了简单的输入校验,避免因字符数量不足导致数组越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 04:35:33