String split and NumberFormatException

Here is one interesting catch

I was trying to convert a string with spaces into various subparts

So i used split method and then tried to convert the individual values into int

While parsing int values i was getting NumberFormatException

That seems very strange at first instance but yes i got it.

After careful notice i found that

19 String[] input = line.split("\\s+");
20 System.out.println(input[0]);
21 int withdrawl = Integer.parseInt("input[0]");

Line 21 already had " " quotes inserted in array generated by the split method

So just


19 String[] input = line.split("\\s+");
20 System.out.println(input[0]);
21 int withdrawl = Integer.parseInt(input[0]);

without quotes was enough to parse the value

The javadoc for split method explains more

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }

No comments:

Post a Comment

Please share your views and comments below.

Thank You.