user567
user567

Reputation: 3852

convert String to int with with parseint

I try to convert int String to int

int port = Integer.parseInt(tokens[2]);

tokens[2] contain a String "12777" But I got this error

Exception in thread "Thread-2019" java.lang.NumberFormatException: For
 input string:
 "12777" 

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499) 
at inet.ChildServer.hopen(ChildServer.java:88)  
at inet.ChildServer.run(ChildServer.java:51)

Edit: Sorry the characters are invisible in eclipse, I don't Understand what is this. I have a String in this form

command1|Destination-IP|DestinationPort

and I just splot it

String[] tokens = sentence.split( "[|]" );

Upvotes: 0

Views: 154

Answers (3)

Jonas Libbrecht
Jonas Libbrecht

Reputation: 777

Be careful you can have errors after you

String x = "123";
Integer.parseInt(x);

do

String x = "jonas";
try{
Integer.parseInt(x.trim());
catch(NumberFormatException e){
    //do something creative with the error
}

Upvotes: 0

java seeker
java seeker

Reputation: 1266

can you trim the string before pass to Integer.parseInt(tokens[2]); it may contain blank spaces.

Upvotes: 1

AlexR
AlexR

Reputation: 115328

As have guys already mentioned your string does not contain 12777 as you think. It contains 12777 and then a lot of garbage that prevents parsing of your string to int. Debug your code to understand what is the source of this garbage. Take a look on code that assigns value to tokens[2].

If you have problems there post the code that assigns value to tokens[2].

Good luck.

EDIT

OK, you have posted yet another part of your code. But the problems seems to be before this point. Take a look on code that assigns value to sentence.

BTW: you can see everything in eclipse. Expand the string and see the character array stored into the string.

Upvotes: 0

Related Questions