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

Java中使用Math.random()生成指定长度数字字符串并按规则分组的实现问题

Fixing Your String Grouping Issue with Simple Adjustments

Hey there! Let's break down why your current grouping code is causing errors and fix it with straightforward, easy-to-understand changes.

What's Wrong with the Original Grouping Code?

Your loop has three key issues that lead to messy output and StringIndexOutOfBoundsException:

  • Incorrect loop condition: i <= length makes you try to access positions way beyond the string's actual length.
  • Fixed end index in substring: Using substring(i, 3) or substring(i, 2) doesn't offset from your current i position — it always tries to grab up to index 3 or 2, which is totally not what you want for grouping.
  • No step increment: You're not increasing i by the group size (2 or 3) each iteration, so you're reprocessing the same characters over and over.

Simple Fix for Grouping Logic

Here's how to adjust your code to handle grouping correctly, even for the final group if it's shorter than the standard size:

First, define your group step size based on the string length, then loop through the string with that step. Use Math.min() to make sure you never go past the string's last character:

// After generating randomString and knowing its length
int step = length > 30 ? 3 : 2;

for (int i = 0; i < length; i += step) {
    // Calculate end index: don't go beyond the string's length
    int endIndex = Math.min(i + step, length);
    String group = randomString.substring(i, endIndex);
    System.out.println("Group: " + group);
}

Full Integrated Example

Let's put it all together in your stringAdd() method to make it work end-to-end:

public class StringGrouping {
    public static void stringAdd(int length) {
        // Generate the random digit string
        String randomString = "";
        for(int i = 0; i < length; i++) {
            int numbers = (int)(Math.random()*10);
            randomString = randomString + numbers;
        }
        System.out.println("Generated string: " + randomString);

        // Group the string correctly
        int step = length > 30 ? 3 : 2;
        for (int i = 0; i < length; i += step) {
            int endIndex = Math.min(i + step, length);
            System.out.println("Group: " + randomString.substring(i, endIndex));
        }
    }

    public static void main(String[] args) {
        // Generate random length between 25-50 inclusive
        int randomLength = (int)(Math.random() * (50 - 25 + 1)) + 25;
        stringAdd(randomLength);
    }
}

Testing with Your Example

For your test case where length = 30 (so step = 2), the code will split the string 445870958423418563903977492822 into clean groups like:

Group: 44
Group: 58
Group: 70
...
Group: 22

Which matches your expected output, with no index errors at all.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 13:39:08