java - Handling possibility of empty parseInt -
i have string, , extract text between 2 special characters.
(my text numbers, example -- hi%773%what -- 773)
i use praseint change substring of numbers integer(which successful).
where program crashes , burns (praseint numformat exception) , when string contains no numbers between special characters.
my_string = "heyhow$98765$you" works, 98765 , can parseint
.
my_string = "heyhow$$areyou" runtime error
.
string str = "heyhow$$areyou"; int startindex = str.indexof('$'); int lastindex = str.indexof('$', i+1); string nums = str.substring(startindex + 1, lastindex); int stringnumber = integer.parseint(nums); <--runtime error cause of no# parse
thank in advance help. if have idea not involve using loop or conditional statement best!
use instead:
int stringnumber = nums.length() > 0 ? integer.parseint(nums) : 0;
this parse number if length not zero, otherwise set stringnumber
value 0
. change if want different value empty string.
this still fail if string between delimiters not valid number. if possibility:
int stringnumber = 0; try { stringnumber = integer.parseint(nums); } catch (numberformatexception nx) // depends on how want handle invalid numbers }
Comments
Post a Comment