1

假设我有以下变量:

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

最好的存储方式是:“02071231234”、“02071231235”、“02071231236”、“02071231237” numbersFromStartToEnd

我尝试更改Stringtoint并希望使用循环来创建字符串列表:

int startInt = Integer.parseInt(start);

但我得到

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

我想这是因为这个数字有一个前导零。

4

3 回答 3

3

问题不在于前导零,请参阅:

int x = Integer.parseInt("0123");
System.out.println(x); // prints 123

问题是你的数字大于Integer.MAX_VALUE

如果我是你,我会将电话号码存储为字符串,或者存储为带有、等PhoneNumber字段的自定义类。country codearea codenumber


更新:如果您的字符串由数字组成,您可以通过以下方法检查一个数字是否介于其他两个数字之间:

    String start   = "02071231234"; 
    String end     = "02071231237";
    String toCheck = "02071231235";
    if (start.compareTo(toCheck) < 0 && end.compareTo(toCheck) > 0) {
        System.out.println("toCheck is between start and end");
    } else {
        System.out.println("toCheck is NOT between start and end");
    }
于 2013-07-08T20:53:50.267 回答
0

我不确定任何响应都是实际的解决方案。我创建了一小段代码,它给出了["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);
    }
}
于 2013-07-08T21:20:45.500 回答
0

问题是您的数字大于最大可能的整数值

Integer.MAX_VALUE = 2147483647

使用BigInteger这样的

BigInteger myBigInt = new BigInteger("my String");

然后你仍然可以做得到myBigInt + 1下一个

Integer或者,如果您确实修剪了前导零,只要您的数字不超过,您就应该可以使用Integer.MAX_VALUE

于 2013-07-08T20:56:18.333 回答