NumberFormatException when converting Integer Stri

2020-04-10 00:52发布

I declare this variable:

private String numCarteBancaireValide=String.valueOf(((Integer.parseInt(Config.NUM_CARTE_BANCAIRE_VALIDE)   ) + (Integer.parseInt("0000000000000001"))));
Config.NUM_CARTE_BANCAIRE_VALIDE is a string.

After Execution, I receive this error message :

java.lang.NumberFormatException: For input string: "4111111111111111"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at java.lang.Integer.parseInt(Integer.java:615)

Please, Can you give your advices ?

标签: java
4条回答
迷人小祖宗
2楼-- · 2020-04-10 01:25

The 4111111111111111 (which most likely is the value of Config.NUM_CARTE_BANCAIRE_VALIDE) overflows the Integer type.

Better try with:

//if you need a primitive
long value = Long.parseLong(Config.NUM_CARTE_BANCAIRE_VALIDE); 

or

//if you need a wrapper
Long value = Long.valueOf(Config.NUM_CARTE_BANCAIRE_VALIDE); 
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-04-10 01:32

Integer.parseInt will attempt to parse an integer from a String.

Your "4111111111111111" String does not represent an valid Java integer type, as its value would be > Integer.MAX_VALUE.

Use Long.parseLong instead.

查看更多
乱世女痞
4楼-- · 2020-04-10 01:44

Use Long.parseLong(), as your parameter is too large for an Integer. (Maximum for an integer is 2147483647)

PS: using Integer.parseInt("0000000000000001") doesn't make much sense either, you could replace this with 1.

查看更多
▲ chillily
5楼-- · 2020-04-10 01:45

The maximum value of integer is 2147483647. So you need to use Long.parseLong instead to parse 4111111111111111. Something like this:

long l = Long.parseLong("4111111111111111");

On a side note:

As Alex has commented, if this number is representing a credit card number then you can treat it like a string instead of changing to long as there is no arithmetic calculations involved with the credit card numbers.

查看更多
登录 后发表回答