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

Java二维数组动态插入子串遇索引越界,求解决方案

解决字母汤程序的StringIndexOutOfBoundsException问题

错误根源

你遇到的StringIndexOutOfBoundsException核心原因有两个:

  • x和y会在循环中持续自增,没有在处理新单词时重置,很快就会超出当前单词的长度范围,触发索引越界。
  • substring(x++, y++)的用法错误,要提取单个字符,应该用substring(pos, pos+1),而非同时递增两个索引。

另外你的循环逻辑也存在混乱:当前代码会在每轮j循环中重复判断是否输入单词,导致输入逻辑与填充逻辑混杂,且未控制每个单词仅填充对应长度的连续列位置。

修正方案

核心调整点

  1. 分离输入与填充逻辑:先一次性收集5个符合要求的单词,避免在矩阵循环中反复触发输入。
  2. 重置字符索引:每次处理新单词时,从第一个字符开始提取,避免索引累积溢出。
  3. 正确提取单个字符:用charAt(pos)直接获取单个字符(再转为字符串),比substring更直观且不易出错。
  4. 控制填充边界:确保单词填充到随机行的连续列时,不会超出矩阵的列范围(20列)。

修正后的代码

import java.util.Scanner;
import java.util.Random;

public class WordSoup {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        Random random = new Random();
        
        // 先收集5个符合要求的单词
        String[] words = new String[5];
        for (int w = 0; w < 5; w++) {
            System.out.println("Enter word between 3 and 5 characters");
            String word = read.next();
            while (word.length() > 5 || word.length() < 3) {
                System.out.println("Must have between 3 and 5 characters");
                word = read.next();
            }
            words[w] = word;
        }
        
        // 初始化20x20矩阵
        String matrix[][] = new String[20][20];
        // 先把所有位置设为空字符串,方便后续补全随机字母
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                matrix[i][j] = "";
            }
        }
        
        // 将每个单词填充到随机行的连续列中
        for (String word : words) {
            int randomRow = random.nextInt(20); // 随机选0-19的行
            // 计算合法的起始列,确保单词不会超出矩阵右边界
            int startCol = random.nextInt(20 - word.length() + 1);
            
            for (int pos = 0; pos < word.length(); pos++) {
                // 提取单个字符放入矩阵对应位置
                matrix[randomRow][startCol + pos] = String.valueOf(word.charAt(pos));
            }
        }
        
        // 补全矩阵空白位置为随机字母,并打印结果
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                if (matrix[i][j].isEmpty()) {
                    matrix[i][j] = String.valueOf((char)('A' + random.nextInt(26)));
                }
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
        
        read.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:17:14