说我有以下变量:

String start = "02071231234";
String end = "02071231237";
List<String> numbersFromStartToEnd = new ArrayList<String>();


最佳存储方式是:numbersFromStartToEnd中的“ 02071231234”,“ 02071231235”,“ 02071231236”,“ 02071231237”。

我尝试将String更改为int,并希望使用循环来创建字符串列表:

int startInt = Integer.parseInt(start);


但我越来越

java.lang.NumberFormatException: For input string: "02885449730"


我猜是因为数字的前导零。

最佳答案

我不确定任何回应是否是实际的解决方案。我创建了一些代码,该代码给出了您正在寻找的结果(["02071231234", "02071231235", "02071231236", "02071231237"]):

public static void main(String[] args) {
    String start = "02071231234";
    String end = "02071231237";
    String leadingZeros = "";
    List<String> numbersFromStartToEnd = new ArrayList<String>();

    // get leading zeros (makes the assumption that all numbers will have same qty of leading zeros)
    for(char digit : start.toCharArray()) {
        if(digit != '0') { break; }
        leadingZeros += "0";
    }

    // set up your BigInts
    BigInteger s = new BigInteger(start);
    BigInteger e = new BigInteger(end);
    BigInteger one = new BigInteger("1");

    // collect all numbers from start to end (adding on any leading zeros)
    while (s.compareTo(e) <= 0) {
        numbersFromStartToEnd.add(leadingZeros + s.toString());
        s = s.add(one);
    }

    // print the result
    for(String string: numbersFromStartToEnd) {
        System.out.println(string);
    }
}

10-06 06:13