java - return the sum of all integers -
program should return sum of numbers in string.
public static void main(string[] args) { string data = "1a2b-3c"; data=data.replaceall("[\\d]+"," "); string[] numbers=data.split(" "); int sum = 0; for(int i=0;i<numbers.length;i++){ try{ sum+=integer.parseint(numbers[i]); } catch( exception e ) { e.printstacktrace(); } } system.out.println("the sum is:"+sum); }
so above input, should return sum 0 ==> (1+2 - 3)
but above code returns 6. right regex this?
here's how should it
string data = "1a2b-3c"; int sum=0; pattern p = pattern.compile("-?\\d+"); matcher m = p.matcher(data); while (m.find()) { sum+=integer.parseint(m.group()); }
Comments
Post a Comment