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

Java中将字符串集合转为字符二维数组出现越界异常如何解决

问题根因
  • 二维数组的维度定义顺序错误:Java 二维数组的声明规则为char[行数][每行元素数],你需要存储h个字符串(对应h行),每个字符串有w个字符(对应每行w个元素),但你的代码写的是char[][] answer = new char[w][h];,将行数和列数的位置颠倒了。当外层循环i遍历到大于等于w的数值时,访问answer[i]就会超出数组第一维的长度,触发数组越界异常,你遇到的Index 9 out of bounds for length 9就是这个原因导致的。
修复方法

仅需要调整二维数组初始化的维度顺序即可,修改后的完整代码如下:

import java.util.*;
import java.io.*;
import java.math.*;

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
class Solution {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int w = in.nextInt(); // width of the strings
        int h = in.nextInt(); // number of strings
        // 调整维度顺序:第一维是行数h,第二维是每行字符数w
        char[][] answer = new char[h][w];
        if (in.hasNextLine()) {
            in.nextLine();
        }
        for (int i = 0; i < h; i++) {
            String line = in.nextLine();
            for(int j = 0; j < w; j++){
                answer[i][j] = line.charAt(j);
                System.out.print(answer[i][j]);
             }
            // 可选:每行输出完添加换行,更符合阅读习惯
            System.out.println();
        }
    }
}
可选优化建议
  • 可以增加输入字符串长度校验,避免输入的字符串长度不足w时,line.charAt(j)也触发字符串索引越界异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:00:05