Java中使用Math.random()生成指定长度数字字符串并按规则分组的实现问题
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 <= lengthmakes you try to access positions way beyond the string's actual length. - Fixed end index in substring: Using
substring(i, 3)orsubstring(i, 2)doesn't offset from your currentiposition — 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
iby 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

