我有一个 JSON 请求负载,需要传递 2 个值: value-1- 这是 10 位数字的随机数示例:8000000000 value-2-这是一个递增的数字,但只有子字符串,其中仅包含 value-1 递增数字的最后 4 位数字-即,如果我将 80000000000 (这是我的 value-1)增加 1000,我将得到 8000001000,所以在值 2 中,我只想显示最后 4 位数字,即 1000
我使用下面的代码生成了 value-1 的随机字符串-
Generex generex = new Generex(regex); //where regex is 8605005[0-9]{3}
String randomString = generex.random();
System.out.println("This is the Random number->" + randomString);
现在我使用以下代码将字符串解析为整数:
int startnumbervalue;
try {
startnumbervalue = Integer.parseInt(randomString);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println("This is the start number->"+startnumbervalue);
}
它在初始化变量时给出了一个错误,对于 startnumbervalue,但是当我分配 int startnumbervalue = randomstring
时 - 它给出了一个错误,指出将 startnumbervalue
的类型更改为 字符串
。
Also, in my method i have 4 arguments:
`String regex` // to pass the value to get the random number- here i am passing- 8605005[0-9]{3} `String key` // to store the random value generated - this is my value-1 `String counter` // to get the stop range `String endrange` // the counter and the value 1 needs to be added to get the end range and subsequently i need to substring this to get only the last 4 digits.
最佳答案
第一期)
您必须使用一些默认数字初始化您的 startnumbervalue
变量,使用 0 或 -1 或其他值,因为您在 try-catch block 中为其分配一个值,但您的 print 语句不是在那个街区里面。如果您不想分配默认值,则必须将 print 语句放在 try block 内。
第二期)
int 变量可以存储的最大值是 2,147,483,647,但您尝试解析的数字更大,因此它不适合 int 类型。将类型更改为 long。 long 类型变量最多可以存储 9,223,372,036,854,775,807 的值。
Generex generex = new Generex("8605005[0-9]{3}");
String randomString = generex.random();
System.out.println("This is the Random number->" + randomString);
long startnumbervalue = 0; // changed to long
try {
startnumbervalue = Long.parseLong(randomString); // changed to Long.parseLong
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
System.out.println("This is the start number->"+startnumbervalue);
}
在我看来,你根本不需要 try-catch block ,因为你的正则表达式总是返回一个包含十位数字的字符串。您可以完全删除它:
Generex generex = new Generex("8605005[0-9]{3}");
String randomString = generex.random();
System.out.println("This is the Random number->" + randomString);
long startnumbervalue = Long.parseLong(randomString);
System.out.println("This is the start number->"+startnumbervalue);
long lastFourDigits = startnumbervalue % 10000;
System.out.println("last four digits: "+lastFourDigits);
关于java - 如何将随机字符串转换为整数以派生另一个整数,然后将它们转换为字符串以发送到 JSON 有效负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58199090/