Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert String to int in Java

Tags:

java

In my program I need to convert a String to Int.

    String str = new String(request.getData());

    String [] setting = str.split(" ");        
    String bs = setting[1];

The value of bs is 1024, I use System.out.println to test it, and it displays on the screen with "1024".

But when I use

    int blockSize = Integer.parseInt(bs); 

it will return an exception point to the line of Integer.parseInt :

Exception in thread "main" java.lang.NumberFormatException: For input string: "1024"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
  at java.lang.Integer.parseInt(Integer.java:458)
  at java.lang.Integer.valueOf(Integer.java:554)

Can someone help me to solve it? Thanks.

like image 746
jacobbb Avatar asked Dec 19 '22 11:12

jacobbb


2 Answers

I suspect you have some hidden unicode character in the string bs, you can remove the non-digits with:

bs = bs.replaceAll("\\D", "");
int blockSize = Integer.parseInt(bs);

The code above will also convert the string "1a2" to 12, but that doesn't seem your case.

like image 61
enrico.bacis Avatar answered Jan 01 '23 12:01

enrico.bacis


try this code:

 String bs = setting[1].trim().toString();
like image 41
hossein ketabi Avatar answered Jan 01 '23 13:01

hossein ketabi