我有一个JSON请求有效负载,我需要传递2个值:
value-1-这是10位数的随机数,例如:8000000000
值2-这是一个递增的数字,但仅包含子字符串,该子字符串仅包含值1的递增数的最后4位数字,即如果我将80000000000(即我的值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的类型更改为String


另外,在我的方法中,我有4个参数:

`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块中为其分配了一个值,但您的print语句不在该块内。如果您不想分配默认值,则必须将打印语句放入try块中。

第二期)

一个int变量可以存储的最大值为2,147,483,647,但是您要解析的数字更大,因此它不适合int类型。将类型更改为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块,因为您的正则表达式总是返回一个十位数的字符串。您可以将其完全删除:

    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);

09-10 06:38
查看更多