gpt4 book ai didi

java - 如何在 Java 中创建包含随机生成的数字的字符串列表?

转载 作者:行者123 更新时间:2023-12-01 13:30:42 25 4
gpt4 key购买 nike

我需要能够创建一个函数,生成选定数量的字符串,并添加基于字符串掩码的随机生成的正数。

字符串掩码示例,其中 [n#] 表示具有一定位数的正数:

generateStrings(2, "( (-[n2]) + [n5] )/[n1]");

第一个数字告诉函数要生成多少个字符串。

2个生成的字符串:

( (-23) + 47269 ) / 9

( (-12) + 17935 ) / 1

我希望能够生成数字范围为 1 到 10 位的字符串。

编辑:这是一个可以生成数字范围从 1 到 10 的数字的函数:

public static int generateNumber(int n) {
int m;
if (n==1){
m = (0 + (int)(Math.random() * ((9 - 0) + 1)));
} else if (n==2) {
m = (10 + (int)(Math.random() * ((99 - 10) + 1)));
} else if (n==3) {
m = (100 + (int)(Math.random() * ((999 - 100) + 1)));
} else if (n==4) {
m = (1000 + (int)(Math.random() * ((9999 - 1000) + 1)));
} else if (n==5) {
m = (10000 + (int)(Math.random() * ((99999 - 10000) + 1)));
} else if (n==6) {
m = (100000 + (int)(Math.random() * ((999999 - 100000) + 1)));
} else if (n==7) {
m = (1000000 + (int)(Math.random() * ((9999999 - 1000000) + 1)));
} else if (n==8) {
m = (10000000 + (int)(Math.random() * ((99999999 - 10000000) + 1)));
} else if (n==9) {
m = (100000000 + (int)(Math.random() * ((999999999 - 100000000) + 1)));
} else if (n==10) {
m = (1000000000 + (int)(Math.random() * ((2147483647 - 1000000000) + 1)));
}
return m;
}

现在我只需要能够将该函数应用于字符串掩码。

EDIT3:这是一个脚本,应生成具有上述格式的字符串掩码的单个字符串:

    public static String generateString(String mask) {
for (int i = 1; i < 10; i++)
{
String searchString = "[n" + i + "]";
int lastIndex = 0;
int count = 0;
while(lastIndex != -1){

lastIndex = mask.indexOf(searchString,lastIndex);

if( lastIndex != -1){
count ++;
lastIndex+=searchString.length();
}
}

for (int j=count; j > 0;) {
while(lastIndex != -1){

lastIndex = mask.indexOf(searchString,lastIndex);

if( lastIndex != -1){
count ++;
lastIndex+=searchString.length();
}
}
mask = mask.replaceFirst(searchString, String.valueOf(generateNumber(i)));
}

}
return mask;
}

我不知道这个脚本是否有效,也不知道如何测试我的代码,所以如果有人验证它是否有效,我将不胜感激。这段代码的一部分来自ansible的回答,另一部分来自codebreach对这个问题的回答:Occurrences of substring in a string我只是想赞扬他们所做的工作。

最佳答案

如果你想从头开始学习 Java,你可以从生成 random int 开始。 ,转换此 int to a String 。该字符串可用于 build您想要的输出。

但是如果你很懒,只想写一行代码,你可以使用 RandomStringUtils from the apache commons library 。但是,这假设您知道如何将外部库添加到类路径中。

String out = RandomStringUtils.randomNumeric(n);

关于java - 如何在 Java 中创建包含随机生成的数字的字符串列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21587848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com